如何将CommandParameter绑定到未知的父项

问题描述:

我在我的应用程序资源中声明了以下上下文菜单,它在我的应用程序中由几个树视图引用。我想发送TreeView的SelectedItem属性作为命令参数。如何将CommandParameter绑定到未知的父项

问题是,我无法弄清楚如何让命令发送TreeView的SelectedItem。

该参数始终为空。我曾尝试使用相对来源,模板化的父母等。以及寻找treeview,treeviewitem和简单的datacontext的目标。我也尝试发送这些项目的不同属性(不只是TreeView的SelectedItem)。我似乎无法解决任何问题。

<Application.Resources> 
    <ContextMenu x:Key="ContextMenu.TreeView"> 
     <MenuItem 
      Header="Add Node" 
      Command="{Binding AddNodeCommand}" 
      CommandParameter="{Binding Path=SelectedItem, RelativeSource={RelativeSource AncestorType={x:Type TreeView}}}"></MenuItem> 
     <MenuItem 
      Header="Delete Node" 
      Command="{Binding DeleteNodeCommand}" 
      CommandParameter="{Binding Path=SelectedItem,RelativeSource={RelativeSource AncestorType={x:Type TreeView}}}"></MenuItem> 
    </ContextMenu> 
</Application.Resources> 

<UserControl ...> 
    <TreeView 
     x:Name="TaxonomyTree" 
     ItemsSource="{Binding Path=Tree}"   
     ContextMenu="{StaticResource ContextMenu.TreeView}"/> 
</UserControl> 

尝试:

<ContextMenu x:Key="ContextMenu.TreeView"> 
    <MenuItem Command="{Binding AddNodeCommand}" 
      CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, 
                     AncestorType={x:Type ContextMenu}}, 
             Path=PlacementTarget.SelectedItem}" 
      Header="Add Node" /> 
    <MenuItem Command="{Binding DeleteNodeCommand}" 
      CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, 
                     AncestorType={x:Type ContextMenu}}, 
             Path=PlacementTarget.SelectedItem}" 
      Header="Delete Node" /> 
</ContextMenu> 

Contextmenu是不一样的视觉树,因为它链接对TreeView的一部分。所以我们需要使用PlacementTarget来相应地路由到TreeView