我有一个TreeViewItem的HierarchicalDataTemplate,在模板中我有一个上下文菜单,我想作为CommandParameter传递ContextMenu父级 - 即此时右键单击的TreeViewItem所有者,有没有办法做到这一点? 这是我的模板:
<HierarchicalDataTemplate
x:Key="ServerTemplate"
DataType="{x:Type models:Server}"
ItemsSource="{Binding Channels}"
ItemTemplate="{StaticResource ChannelTemplate}">
<StackPanel
Tag="{Binding DataContext,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Window}}}"
Orientation="Horizontal">
<StackPanel.ContextMenu>
<ContextMenu
FontSize="14"
FontFamily="Arial">
<MenuItem
Header="{x:Static p:Resources.ServerOperations_CommunicationSettings}"
Command="{Binding PlacementTarget.Tag.ServerCommunicationSettingCommand, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ContextMenu}}}"
CommandParameter="{Binding Path=Parent, RelativeSource={RelativeSource Mode=Self}}">
</MenuItem>
</ContextMenu>
</StackPanel.ContextMenu>
<Image
Source="{Binding ImageURL, Converter={StaticResource StringToImageConverter}}"
Margin="0,0,2,0"
Height="25"
Width="25"/>
<TextBlock
Text="{Binding ServerName}"
Foreground="White"/>
</StackPanel>
</HierarchicalDataTemplate>
感谢您的帮助
答案 0 :(得分:2)
您可以通过PlacementTarget of ContextMenu
获取StackPanel
来获取TreeViewItem,TemplatedParent
将ContentPresenter
,TemplatedParent
将TreeViewItem
CommandParameter="{Binding Path=PlacementTarget.TemplatedParent.TemplatedParent,
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType={x:Type ContextMenu}}}"
}。所以这将有效:
Server
PlacementTarget(StackPanel) - &gt; TemplatedParent(ContentPresenter) - &gt; TemplatedParent(TreeViewItem)
理想情况下,将UI组件传递给ViewModel 并不是一个好主意。您应该传递数据,即TreeViewItem的DataContext,因为您始终可以使用它。
如果您想要传递DataContext
实例,即TreeviewItem的"{Binding}"
,您只需执行CommandParameter="{Binding}"
,因为MenuItem将从StackPanel继承它。
{{1}}