获取父节点的ContextMenu数据上下文
本文关键字:数据 上下文 ContextMenu 父节点 获取 | 更新日期: 2023-09-27 18:04:13
我有一个ContextMenu绑定到一个CommandBinding:
<MetroTreeView:MetroTreeView x:Name="tvTagList" Grid.Row="1" Margin="15, 0, 15, 0" SelectedItemChanged="tvTagList_SelectedTagChanged" ItemsSource="{Binding}" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Background="{x:Null}" BorderBrush="{DynamicResource ExtryzeAccentBrushSecondary}" BorderThickness="2" Foreground="White"
VirtualizingStackPanel.IsVirtualizing="True" VirtualizingStackPanel.VirtualizationMode="Standard">
<MetroTreeView:MetroTreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type DataBind:TagClass}" ItemsSource="{Binding Children}" >
<StackPanel Orientation="Horizontal" HorizontalAlignment="Stretch">
<TextBlock>
<Run Text="{Binding TagClassMagic}" />
<Run Foreground="{StaticResource TextBrushSecondary}" Text=" - " />
<Run Foreground="{StaticResource TextBrushSecondary}" Text="{Binding Path=Description, Converter={StaticResource IValueTagDescriptionCleanup}}" />
</TextBlock>
<StackPanel.ContextMenu>
<ContextMenu>
<MenuItem Header="Dump Tag List..." Click="DumpClassTagList" />
</ContextMenu>
</StackPanel.ContextMenu>
</StackPanel>
</HierarchicalDataTemplate>
<DataTemplate DataType="{x:Type DataBind:TagEntry}">
<StackPanel Orientation="Horizontal" HorizontalAlignment="Stretch">
<StackPanel.ContextMenu>
<ContextMenu>
<ContextMenu.CommandBindings>
<CommandBinding Command="{x:Static DataBind:HaloMap.CommandTagBookmarking }"
CanExecute="CommandTagBookmarking_CanExecute"
Executed="CommandTagBookmarking_Executed"
/>
</ContextMenu.CommandBindings>
<MenuItem Header="Bookmark Tag" Foreground="White" Command="{x:Static DataBind:HaloMap.CommandTagBookmarking}" CommandParameter="{Binding}" />
</ContextMenu>
</StackPanel.ContextMenu>
<TextBlock Text="{Binding TagFileName}" />
</StackPanel>
</DataTemplate>
</MetroTreeView:MetroTreeView.Resources>
<MetroTreeView:MetroTreeView.ItemContainerStyle>
<Style TargetType="{x:Type MetroTreeView:MetroTreeViewItem}" BasedOn="{StaticResource {x:Type MetroTreeView:MetroTreeViewItem}}">
<EventSetter Event="MouseDoubleClick" Handler="tvTagList_ItemDoubleClick" />
</Style>
</MetroTreeView:MetroTreeView.ItemContainerStyle>
但是当我运行CanExecute
命令时,每次访问DataContext的尝试总是遇到null:
private void CommandTagBookmarking_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
var a = e.Source;
var b = ((MenuItem)a).DataContext;
var c = ((ContextMenu) ((MenuItem) e.Source).Parent).DataContext;
}
试试这个:
<ContextMenu DataContext="{Binding PlacementTarget, RelativeSource={RelativeSource Self}}">
由于ContextMenu
不位于对象的VisualTree
中,因此它被放置。您必须使用PlacementTarget
-
DataContext
<ContextMenu DataContext="{Binding PlacementTarget.DataContext,
RelativeSource={RelativeSource Self}}">