我正在尝试按名称将元素绑定到ContextMenu中的MenuItem。要绑定的元素:
<UserControl x:Class="ATCheckerView.TestsPropagate"
x:Name="TestPropagateRoot" ...
工作版:
<HierarchicalDataTemplate x:Key="SchemTemplate">
<Button Command="{Binding ElementName=TestPropagateRoot, Path=DataContext.vclient.OpenInViewer}" />
</HierarchicalDataTemplate>
非工作:
<HierarchicalDataTemplate x:Key="SchemTemplate">
<TextBlock Text="{Binding path}">
<TextBlock.ContextMenu>
<ContextMenu>
<MenuItem Header="{Binding ElementName=TestPropagateRoot}"
Command="{Binding ElementName=TestPropagateRoot, Path=DataContext.vclient.OpenInViewer}"
CommandParameter="{Binding}" />
</ContextMenu>
</TextBlock.ContextMenu>
</TextBlock>
</HierarchicalDataTemplate>
答案 0 :(得分:1)
here是一个类似的问题和一个很好的答案,它显示了如何处理contextmenu绑定的一些方法。
btw大部分时间都使用PlacementTarget绑定,例如
<TextBlock Text="{Binding path}">
<TextBlock.ContextMenu>
<ContextMenu>
<MenuItem Header="Test"
Command="{Binding Path=PlacementTarget.DataContext.vclient.OpenInViewer,
RelativeSource={RelativeSource AncestorType=ContextMenu}}"
CommandParameter="{Binding}" />
</ContextMenu>
</TextBlock.ContextMenu>
</TextBlock>
编辑:{x:参考TestPropagateRoot}也可以是一个选项,如果您使用.net4.0
答案 1 :(得分:0)
我的解决方案是:
<HierarchicalDataTemplate x:Key="SchemTemplate">
<TextBlock Text="{Binding path}"
Tag="{Binding DataContext, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type local:TestsPropagate}}}">
<TextBlock.ContextMenu>
<ContextMenu>
<MenuItem Header="Открыть для просмотра"
Command="{Binding Path=PlacementTarget.Tag.vclient.OpenInViewer,
RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContextMenu}}"
CommandParameter="{Binding}" />
</ContextMenu>
</TextBlock.ContextMenu>
</TextBlock>
</HierarchicalDataTemplate>