将contextmenu父级作为CommandParameter传递 [英] pass contextmenu parent as CommandParameter
问题描述
我有一个TreeViewItem的HierarchicalDataTemplate,在模板中有一个contextmenu,我想将ContextMenu父级作为CommandParameter传递-即目前右键单击的TreeViewItem所有者,有没有办法做到这一点?
这里是我的模板:
i have a HierarchicalDataTemplate for a TreeViewItem, in the template i have a contextmenu and i want to pass as CommandParameter the ContextMenu parent - i.e the TreeViewItem owner that was right clicked at the moment, is there a way to do that? here is my template:
<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>
感谢帮助
推荐答案
您可以通过获取ContextMenu的 PlacementTarget
来获取TreeViewItem,该菜单将为 StackPanel
及其 TemplatedParent
将为 ContentPresenter
,其 TemplatedParent
将为 TreeViewItem
。这样就可以了:
You can get the TreeViewItem by getting PlacementTarget of ContextMenu
which will be StackPanel
and its TemplatedParent
will be ContentPresenter
and its TemplatedParent
will be TreeViewItem
. So this will work:
CommandParameter="{Binding Path=PlacementTarget.TemplatedParent.TemplatedParent,
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType={x:Type ContextMenu}}}"
PlacementTarget(StackPanel)-> TemplatedParent(ContentPresenter)-> TemplatedParent(TreeViewItem)
将UI组件传递给ViewModel并不是一个好主意。您应该传递数据,例如TreeViewItem的DataContext,因为您可以随时使用它。
Ideally it's not a good idea to pass UI components to ViewModel. You should pass data i.e. DataContext of TreeViewItem as you can always play with that.
如果您想传递 Server
实例,即TreeviewItem的 DataContext
,您只需执行 {Binding}
MenuItem将从StackPanel继承它。
In case you want to pass Server
instance i.e. DataContext
of TreeviewItem, you can simply do "{Binding}"
since MenuItem will inherit it from StackPanel.
CommandParameter="{Binding}"
这篇关于将contextmenu父级作为CommandParameter传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!