我有一个绑定到某些属性类型的 Observable 集合的树视图。有一个 HierarchicalDataTemplate 在树视图中显示数据。现在我需要显示每个 HierarchicalDataTemplate 项目的特定上下文菜单。
我使用以下 XAML 来显示上下文菜单:
<HierarchicalDataTemplate ItemsSource="{Binding Collections}">
<TextBlock Text="{Binding Path=Name}">
<TextBlock.ContextMenu>
<ContextMenu>
<MenuItem Header="Create" Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}, Path=DataContext.AddCommand}" CommandParameter="{Binding}"/>
</ContextMenu>
</TextBlock.ContextMenu>
</TextBlock>
</HierarchicalDataTemplate>
这里,AddCommand 被写入视图模型中,并在控制下绑定到此视图模型。
我可以看到上下文菜单,但单击菜单项时不会触发事件。
请帮忙..
您的命令绑定将不起作用,因为 ContextMenu 与您的 UserControl 不在同一逻辑树上,因此它将找不到 UserControl 祖先。但是,您的 ContextMenu 应自动继承其容器的数据上下文。
所以这应该有效 -
<ContextMenu>
<MenuItem Header="Create" Command="{Binding AddCommand}" CommandParameter="{Binding}"/>
</ContextMenu>
但是,AddCommand 属性应该存在于 HierarchicalDataTemplate 绑定项上。
EDIT:
如果您的命令未在 HierarchicalDataTemplate 的绑定项中定义,而是在 UserControl 中定义。然后,您可以尝试的另一个想法是为您的 UserControl 指定一个名称,然后通过 ElementName 将命令绑定到它。像这样
再次更新:
<ContextMenu>
<MenuItem Header="Create" Command="{Binding ElementName="MyUserControl" Path="DataContext.AddCommand"}" CommandParameter="{Binding}"/>
</ContextMenu>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)