我有一个绑定到 CommandBinding 的 ContextMenu:
<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 的尝试总是遇到一个空值:
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;
}