RelativeSource绑定无法解析 [英] RelativeSource binding not resolving

查看:87
本文介绍了RelativeSource绑定无法解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在TreeView中有一个ContextMenu

I have a ContextMenu in a TreeView

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

我想将ContextMenuItem的命令绑定到在ViewModel的RelayCommand中,我尝试了各种RelativeSource绑定,但似乎无济于事...

I want to bind the Command of the ContextMenuItem to a RelayCommand in the ViewModel, I tried all kinds of RelativeSource bindings, but nothing seems to work...

我应该如何配置RelativeSource绑定?

How should I configure the RelativeSource binding?

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

我遇到诸如

$这样的绑定错误b $ b

找不到参考'RelativeSource
FindAncestor,AncestorType ='System.Windows.Controls.TreeView',
AncestorLevel ='1''的绑定源。
BindingExpression:Path = DataContext.ExcludeSeasonCommand;
DataItem = null;目标元素是 MenuItem(名称=);目标属性
是'Command'(类型为'ICommand')

Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.TreeView', AncestorLevel='1''. BindingExpression:Path=DataContext.ExcludeSeasonCommand; DataItem=null; target element is 'MenuItem' (Name=''); target property is 'Command' (type 'ICommand')


推荐答案

最后,在经过许多Google搜索之后,我遇到了问题解决方法

Finally, after many many many google searches I ran into the solution

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

由于HierarchicalDataTemplate没有出现在可视树中,因此没有相对源...

Because the HierarchicalDataTemplate does not appear in the visual tree, there is not "relative" source...

我希望这对其他正在拔头发的人有所帮助...

I hope this helps somebody else who's pulling his/her hair out...

这篇关于RelativeSource绑定无法解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆