将 WPF ContextMenu MenuItem 绑定到 UserControl 属性与 ViewModel 属性 [英] Binding WPF ContextMenu MenuItem to UserControl Property vs ViewModel Property

查看:60
本文介绍了将 WPF ContextMenu MenuItem 绑定到 UserControl 属性与 ViewModel 属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难理解 ContextMenu 发生了什么.我知道它被渲染为一个单独的窗口,带有一个单独的可视化树,所以我们不能使用相对绑定来绑定作为用户控件属性公开的命令.例如以下不起作用:

I'm struggling to understand what is going on with the ContextMenu. I know it is rendered as a separate window, with a separate visual tree, so we can't use relative binding to bind a command exposed as a property of the user control. e.g. the following does not work:

<MenuItem Command="{Binding RelativeSource={RelativeSource AncestorType=UserControl}, Path=TestCommand}" Header="Test" />

但是,如果您将用户控件的数据上下文设置为将命令作为属性公开的视图模型,则以下操作将起作用:

But, if you set the data context of the user control to a view model that exposes a command as a property, the following will work:

<MenuItem Command="{Binding TestCommand}" Header="Test" />

我不明白的是,如果 ContextMenu 不是可视化树的一部分,它是如何继承 DataContext 的值的.我希望这两个示例的行为相同(即都工作或都失败).

What I don't understand is, how is the ContextMenu inheriting the value of the DataContext if it is not part of the visual tree. I would expect both of these examples to behave the same (i.e. both work or both fail).

推荐答案

第二个绑定之所以有效,是因为所谓的继承上下文".你可以在这里阅读:http://blogs.msdn.com/b/nickkramer/archive/2006/08/18/705116.aspx.基本上这是一种特殊情况,其中某些属性继承所有者对象的数据上下文.因此,例如,继承上下文总是对 Freezable 类型的属性起作用(另一篇关于 Freezables 的有趣文章:http://drwpf.com/blog/category/freezables/).

The second binding works because of so called "inheritance context". You can read about it here: http://blogs.msdn.com/b/nickkramer/archive/2006/08/18/705116.aspx. Basically this is a kind of special case where some properties inherit data context of the owner object. Thus, for example, the inheritance context always works on properties of type Freezable (another interesting article about Freezables: http://drwpf.com/blog/category/freezables/).

实际上这篇文章说继承上下文在 ContextMenu 上不起作用,但在第 4 版中他们添加了它,所以它现在实际上可以正常工作,正如您在示例中所展示的那样.

Actually the article says that the inheritance context doesn't work on ContextMenu, but in version 4 they added it, so it actually works now as you've shown it in your example.

这篇关于将 WPF ContextMenu MenuItem 绑定到 UserControl 属性与 ViewModel 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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