Привязка ContextMenu нарушается - PullRequest
0 голосов
/ 09 марта 2020

HelIo,

У меня проблема случайного прерывания связи с приложением в MVVM, над которым я работаю. Вот сообщение об ошибке, которое у меня есть:

quote System. Windows .Data Error: 4: Не удается найти источник для привязки со ссылкой 'RelativeSource FindAncestor, AncestorType =' System. Windows .Controls .UserControl ', AncestorLevel =' 1 ''. BindingExpression: Path = DataContext.vContextMenuMasters; DataItem = NULL; целевым элементом является ContextMenu (Name = ''); Свойство target - «Visibility» (тип «Visibility»)

quote System. Windows .Data Ошибка: 4: Не удается найти источник для привязки со ссылкой 'RelativeSource FindAncestor, AncestorType =' System. Windows. Controls.UserControl ', AncestorLevel =' 1 ''. BindingExpression: Path = DataContext.dcFilteringControl.AddMasterCommand; DataItem = NULL; Целевым элементом является «MenuItem» (Name = ''); Свойство target: 'Command' (тип 'ICommand') System. Windows .Data Ошибка: 4: Не удается найти источник для привязки со ссылкой 'RelativeSource FindAncestor, AncestorType =' System. Windows .Controls.UserControl ', AncestorLevel = '1'». BindingExpression: (без пути); DataItem = NULL; Целевым элементом является «MenuItem» (Name = ''); Свойство target - 'CommandParameter' (тип 'Object') System. Windows .Data Ошибка: 4: Не удается найти источник для привязки со ссылкой 'RelativeSource FindAncestor, AncestorType =' System. Windows .Controls.Control ', AncestorLevel = '1'». BindingExpression: Path = Foreground; DataItem = NULL; Целевым элементом является «Путь» (Имя = ''); Свойство target - 'Fill' (тип 'Bru sh'). System. Windows .Data Ошибка: 4: Не удается найти источник для привязки со ссылкой 'RelativeSource FindAncestor, AncestorType =' ZSYS.WCTL.WebWindow ', AncestorLevel =' 1 ''. BindingExpression: Path = DataContext.brushTitleBarBackground; DataItem = NULL; Целевым элементом является «MenuItem» (Name = ''); свойство target равно 'Background' (тип 'Bru sh') ...

Мой код:

<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>


Например, каждый раз, когда я запускаю этот код, привязка ломается, но не возникает никакого другого исключения:

        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;
            }

        }

Спасибо за аванс за вашу помощь

РЕДАКТИРОВАТЬ: Если я напишу

<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}}"/>
...

Я получаю неправильную привязку:

цитата Система. Windows .Data Ошибка: 4: Не удается найти источник для привязки со ссылкой 'RelativeSource FindAncestor, AncestorType =' WebWindow ', AncestorLevel =' 1 '' , BindingExpression: Path =; DataItem = NULL; целевой элемент - ListViewItem (Name = ''); Свойство target - «Tag» (тип «Объект»)

Пожалуйста, помогите;)

...