我有一个带有分层数据模板的树视图,我正在尝试为ContextMenu设置DataContext,所以我可以将命令绑定到它。我已经做过研究,并且知道ContextMenu不会继承其父级的DataContext。我试着关注这些帖子:How to set the RelativeSource in a DataTemplate that is nested in a HierarchicalDataTemplate?
How to bind to the DataContext of a HierarchicalDataTemplate from its ItemTemplate XAML?但仍无法让它发挥作用。任何帮助,将不胜感激。这是我的示例代码:
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type viewModels:SiteViewModel}" ItemsSource="{Binding Children}">
<StackPanel Orientation="Horizontal">
<StackPanel.Resources>
</StackPanel.Resources>
<Image Width="16" Height="16" Margin="3,0" />
<TextBlock Text="{Binding SiteName}" />
</StackPanel>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type viewModels:LevelViewModel}" ItemsSource="{Binding Children}" >
<StackPanel Orientation="Horizontal" >
<Image Width="16" Height="16" Margin="3,0" />
<TextBlock Text="{Binding LevelName}" >
<TextBlock.ContextMenu >
<ContextMenu>
<MenuItem Header="Test" Command="{Binding ?????????" CommandParameter="{Binding}"/>
</ContextMenu>
</TextBlock.ContextMenu>
</TextBlock>
</StackPanel>
</HierarchicalDataTemplate>
答案 0 :(得分:0)
解决问题的一种方法: 就我而言,我有类似的东西:
<DataTemplate DataType="...">
<TreeView>
<TreeViewItem Tag="{Binding ElementName=LocalControl, Path=DataContext}"
Header="{Binding ...}"
ContextMenu="{StaticResource ...}">
...
</TreeViewItem>
</TreeView>
</DataTemplate>
您需要将父TreeViewItem的Tag属性绑定到其DataContext,然后在上下文菜单的分层模板中的某处将DataContext绑定到父控件的Tag:
<ContextMenu x:Key="CyclogramFolderContextMenu"
DataContext="{Binding Path=PlacementTarget.Tag, RelativeSource={RelativeSource Self}}">
<TextBlock Text="Do something" >
<TextBlock.InputBindings>
<MouseBinding Command="{Binding Path=(viewModels:someViewModel.SomeCommand)}" MouseAction="LeftClick" />
</TextBlock.InputBindings>
</TextBlock>
</ContextMenu>