0

HelIo,

I have a problem of random broken binding with the application in MVVM I'm working on. Here is the error message I have :

quote System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.UserControl', AncestorLevel='1''. BindingExpression:Path=DataContext.vContextMenuMasters; DataItem=null; target element is 'ContextMenu' (Name=''); target property is 'Visibility' (type 'Visibility')

quote System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.UserControl', AncestorLevel='1''. BindingExpression:Path=DataContext.dcFilteringControl.AddMasterCommand; DataItem=null; target element is 'MenuItem' (Name=''); target property is 'Command' (type 'ICommand') System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.UserControl', AncestorLevel='1''. BindingExpression:(no path); DataItem=null; target element is 'MenuItem' (Name=''); target property is 'CommandParameter' (type 'Object') System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.Control', AncestorLevel='1''. BindingExpression:Path=Foreground; DataItem=null; target element is 'Path' (Name=''); target property is 'Fill' (type 'Brush') System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='ZSYS.WCTL.WebWindow', AncestorLevel='1''. BindingExpression:Path=DataContext.brushTitleBarBackground; DataItem=null; target element is 'MenuItem' (Name=''); target property is 'Background' (type 'Brush')...

My code is :

<UserControl x:Class="UserControls.MastersUserControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             
             xmlns:local="clr-namespace:UserControls"
             
             xmlns:VM="clr-namespace:ViewModels"
             xmlns:Converter="clr-namespace:Classes"
             x:Name="ctlMasterUserControl"
             
             xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
             
             mc:Ignorable="d" 
             d:DesignHeight="984" d:DesignWidth="1280">
    <UserControl.Resources>
        <ContextMenu x:Key="ContextMenuMaster"                     
                     Visibility="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=DataContext.vContextMenuMasters}">
            <MenuItem Header="New"
                      Style="{StaticResource MenuItemStyle}"
                      Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=DataContext.dcFilteringControl.AddMasterCommand}"
                      CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}"
                      >
                <MenuItem.Icon>
                    <Path Width="15"
                          Height="{Binding Path=ActualWidth, RelativeSource={RelativeSource Self}}"
                          Style="{StaticResource Plus}"/>
                </MenuItem.Icon>
            </MenuItem>

            <MenuItem Header="New Master For Export"
                      Style="{StaticResource MenuItemStyle}"
                      Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=DataContext.dcFilteringControl.AddMasterTemplateCommand}"
                      CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}"
                      >
                <MenuItem.Icon>
                    <Path Width="15"
                          Height="{Binding Path=ActualWidth, RelativeSource={RelativeSource Self}}"
                          Style="{StaticResource PlusTemplate}"/>
                </MenuItem.Icon>
            </MenuItem>
...
        </ContextMenu>
    <UserControl.Resources>


     <Grid Grid.Row="1" Background="{StaticResource MainWindowGreyBackground}" ContextMenu="{DynamicResource ContextMenuMaster}">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="Auto"/>
            </Grid.ColumnDefinitions>
...
     </Grid>


For example each time I run this code the binding becomes broken but no other exception is raised :

        private void RefreshData(object obj)
        {
            try
            {                
                Task.Run(async () => await GetMasters()).ContinueWith(a =>
                { //Display the ContextMenu if needed
                    DisplayContextMenuIfNeeded();
                });

            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.ToString(), System.Reflection.Assembly.GetExecutingAssembly().GetName().Name + " : Error", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Exclamation);
            }
        }

        private void DisplayContextMenuIfNeeded()
        {
            //Display the context Menu if the option was activated in the settings
            if (MainWindowViewModel.objUIParameters != null)
            {
                if (MainWindowViewModel.objUIParameters.bIsCheckedShowContextMenu) vContextMenuMasters = Visibility.Visible;
                else vContextMenuMasters = Visibility.Collapsed;
            }

            if ((bool)Application.Current.Properties["Valid"])
            {
                vCloneMasterMenyEntry = Visibility.Visible;
            }
            else
            {
                vCloneMasterMenyEntry = Visibility.Collapsed;
            }
            
        }

Thanks per advance for your help

EDIT : If I write

<Grid Grid.Row="1" ContextMenu="{DynamicResource ContextMenuMaster}" Tag="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=WCTL602:WebWindow}}">
...
<ListView.ItemContainerStyle>
     <Setter Property="ContextMenu" Value="{DynamicResource ContextMenuMaster}" />
     <Setter Property="Tag" Value="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=WCTL602:WebWindow}}"/>
...

I obtain a broken binding :

quote System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='WebWindow', AncestorLevel='1''. BindingExpression:Path=; DataItem=null; target element is 'ListViewItem' (Name=''); target property is 'Tag' (type 'Object')

Please help ;)

Community
  • 1
  • 1
Le ZVince
  • 39
  • 7
  • Does this answer your question? [WPF ContextMenu woes: How do I set the DataContext of the ContextMenu?](https://stackoverflow.com/questions/15033522/wpf-contextmenu-woes-how-do-i-set-the-datacontext-of-the-contextmenu) – dymanoid Mar 09 '20 at 10:52
  • Thanks for your answer it has been helped me, but on a if I write I obtain a broken binding, please help ;) I edited the main post to show it – Le ZVince Mar 09 '20 at 15:21
  • With your solution dymanoid I have a lot of problem of broken bindings is there another way to fix that ? – Le ZVince Mar 10 '20 at 08:47
  • Is the dymanoid's solution the best way to do with the ContextMenu ? – Le ZVince Mar 10 '20 at 14:35
  • The `ContextMenu` in WPF does not belong to the visual tree of the element the menu is attached to. You have to keep that in mind. With this knowledge, you can implement a different solution - not exactly as described in the question I linked. – dymanoid Mar 10 '20 at 15:13

0 Answers0