Как отключить MenuItems на основе DataGrid DependencyProperty в WPF ContextMenu - PullRequest
1 голос
/ 03 марта 2020

Я пытаюсь добиться следующего:

Проекты основаны на среде Prism MVVM. В моем основном ResourceDictionary у меня есть обобщенное c ContextMenu, которое работает для всех моих пользовательских MyDataGrid. Это контекстное меню имеет привязку к ViewModel текущего MyDataGrid, где объявлены некоторые команды. Эта часть уже установлена ​​и работает, как и ожидалось.

Теперь мне нужно также отключить некоторые функции ContextMenu на основе некоторых пользовательских свойств зависимостей MyDataGrid.

Проблема, с которой я сталкиваюсь, заключается в том, что я могу просто добраться до единственного DataGridRow, по которому щелкнули, с помощью PlacementTarget, но не до родительского MyDataGrid, где объявлено свойство зависимости.

Это ContextMenu и это привязка к DataGridRow:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:MyPrismModule.Wpf">

<ContextMenu x:Key="MyCommonContextMenu">
    <MenuItem Header="MyFunction"
              Command="{Binding
                    Path=PlacementTarget.Tag.Template.MyFunction,
                    RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}"
              CommandParameter="{Binding
                    Path=PlacementTarget,
                    RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}">
        <MenuItem.Style>
            <Style TargetType="MenuItem" BasedOn="{StaticResource MaterialDesignMenuItem}">
                <Setter Property="IsEnabled" Value="False"></Setter>
                <Style.Triggers>
                    <DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}, Path=PlacementTarget.Parent.MyDependencyProperty }" Value="True">
                        <Setter Property="IsEnabled" Value="True"></Setter>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </MenuItem.Style>
    </MenuItem>
</ContextMenu>

<Style TargetType="{x:Type DataGridRow}">
    <Setter Property="Tag" Value="{Binding Path=DataContext, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:MyDataGrid}}}"/>
    <Setter Property="ContextMenu" Value="{Binding Source={StaticResource MyCommonContextMenu}}"/>
</Style>

Чтобы добраться до MyDataGrid.MyDependencyProperty, я пробовал этот PlacementTarget.Parent.MyDependencyProperty, но он не работает.

Идея использования Parent изначально была взята отсюда : https://social.msdn.microsoft.com/Forums/vstudio/en-US/1b01ba4e-d6a8-4e95-b8a0-bd3633bca2bd/binding-to-another-element-inside-a-template?forum=wpf

Спасибо всем, кто найдет время, чтобы разобраться в этом.

1 Ответ

0 голосов
/ 04 марта 2020

На самом деле вы уже сделали всю работу. Небольшое улучшение заключается в установке не DataContext, а MyDataGrid в DataGridRow.Tag и доступ к нему позже через PlacementTarget.Tag.

<ContextMenu x:Key="MyCommonContextMenu">
    <MenuItem Header="{Binding PlacementTarget.Tag.MyDependencyProperty, RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>
    <MenuItem Header="{Binding PlacementTarget.Tag.DataContext.YourViemodelProperty, RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>
</ContextMenu>

<Style TargetType="{x:Type DataGridRow}">
    <Setter Property="Tag" Value="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:MyDataGrid}}}"/>
    <Setter Property="ContextMenu" Value="{Binding Source={StaticResource MyCommonContextMenu}}"/>
</Style>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...