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

查看:1661
本文介绍了绑定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天全站免登陆