1

我在 TreeView 中有一个 ContextMenu

UserControl (DataContext=ViewModel)
    |
    |
    ---- TreeView (ItemSource=MyItems)
           |
           |
           ----- Items (ItemSource=MyChildrenItems)
                   |
                   |
                   ----- ContextMenu

我想将 ContextMenuItem 的命令绑定到 ViewModel 中的 RelayCommand,我尝试了各种 RelativeSource 绑定,但似乎没有任何效果......

我应该如何配置 RelativeSource 绑定?

<ContextMenu>
    <MenuItem
        Header="Bla"
        Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=TreeView}, Path=DataContext.MyRelayCommand}" />

我收到绑定错误,例如

无法通过引用“RelativeSource FindAncestor,AncestorType='System.Windows.Controls.TreeView',AncestorLevel='1'”找到绑定源。BindingExpression:Path=DataContext.ExcludeSeasonCommand; 数据项=空;目标元素是'MenuItem'(名称='');目标属性是“命令”(类型“ICommand”)

4

2 回答 2

2

最后,经过很多很多谷歌搜索后,我遇到了解决方案

<MenuItem
    Header="Exclude season"
    Command="{Binding DataContext.MyRelayCommand, Source={x:Reference _myTreeView}}" />

因为 HierarchicalDataTemplate 没有出现在可视化树中,所以没有“相对”源...

我希望这可以帮助其他正在拔头发的人......

于 2014-10-06T19:51:51.583 回答
1

另一个常用的解决方案:

<ContextMenu DataContext="{Binding RelativeSource={RelativeSource Self}, Path=PlacementTarget.DataContext}" />
于 2014-10-06T20:28:25.107 回答