我有一个带有分层数据模板的树形视图,并且尝试为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>
最佳答案
一种解决方法:
就我而言,我有这样的事情:
<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>
关于c# - 在树 View 中使用分层数据模板绑定(bind)contextmenu命令,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39702961/