1

我在我的应用程序资源中声明了以下上下文菜单,它被我的应用程序中的几个树视图引用。我正在尝试将 TreeView 的 SelectedItem 属性作为命令参数发送。

问题是我不知道如何获取发送 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>
4

1 回答 1

1

尝试:

<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>

ContextmenuTreeView与它链接的对象不是同一可视树的一部分。所以我们需要使用PlacementTarget来路由到TreeView相应的。

于 2013-07-11T13:45:02.757 回答