我希望能够通过单击上下文菜单中的命令对TreeView中的项执行命令。并且只有当项目属于某种类型时才更具体(xxTreeViewItem是具有2个子类型的接口)。
<Grid Name="Root" commonExtensions:EnterKeyUpdateExtension.IsEnabled="True">
<StackPanel Orientation="Vertical" Grid.Row="0">
<Button Content="Center on" Command="{Binding Path=CenterOnCommand}" Margin="5,10,5,0"/>
</StackPanel>
<Grid>
<TreeView Grid.Row="0" Name="xxTreeView" DataContext="{Binding Path=xxViewModel}" ItemsSource="{Binding Path=Items}">
<TreeView.ItemContainerStyle>
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="ContextMenu">
<Setter.Value>
<ContextMenu>
<MenuItem Header="Center On" Command="{Binding CenterOnCommand}"/>
</ContextMenu>
</Setter.Value>
</Setter>
</Style>
</TreeView.ItemContainerStyle>
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Path=Items}" DataType="{x:Type localViewItems:xxTreeViewItem}">
<TextBlock Text="{Binding Name}" VerticalAlignment="Center"/>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
顶部按钮中的命令有效,但在上下文菜单中不起作用。我尝试了几个绑定并找到了祖先但没有一个可行。是否只有XAML解决方案?
答案 0 :(得分:1)
ContextMenu
不属于可视树,因此它不会继承TreeView的DataContext。因此,您需要使用PlacementTarget属性将其传递给ContextMenu:
<TreeView.ItemContainerStyle>
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="Tag" Value="{Binding RelativeSource={RelativeSource AncestorType=TreeView}, Path=DataContext}"></Setter>
<Setter Property="ContextMenu">
<Setter.Value>
<ContextMenu DataContext="{Binding Path=PlacementTarget.Tag, RelativeSource={RelativeSource Self}}">
<MenuItem Header="Center On" Command="{Binding CenterOnCommand}" />
</ContextMenu>
</Setter.Value>
</Setter>
</Style>
</TreeView.ItemContainerStyle>
我希望它可以帮到你