WPF:绑定文本菜单到MVVM命令 [英] WPF: Binding a ContextMenu to an MVVM Command
问题描述
比方说,我有一个属性返回命令窗口下(事实上,它是在一个ViewModel类的命令的用户控件,但让我们让事情尽可能的简单重现该问题)。
Let's say I have a Window with a property returning a Command (in fact, it's a UserControl with a Command in a ViewModel class, but let's keep things as simple as possible to reproduce the problem).
以下工作:
<Window x:Class="Window1" ... x:Name="myWindow">
<Menu>
<MenuItem Command="{Binding MyCommand, ElementName=myWindow}" Header="Test" />
</Menu>
</Window>
但下面不工作。
<Window x:Class="Window1" ... x:Name="myWindow">
<Grid>
<Grid.ContextMenu>
<ContextMenu>
<MenuItem Command="{Binding MyCommand, ElementName=myWindow}" Header="Test" />
</ContextMenu>
</Grid.ContextMenu>
</Grid>
</Window>
该错误消息我得到的是
The error message I get is
System.Windows.Data错误:4:无法为参照的ElementName = mywindow的绑定找到源头。 BindingEx pression:路径= MyCommand;的DataItem = NULL;目标元素是'菜单项(名称='');目标属性是'命令'(类型'的ICommand')
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'ElementName=myWindow'. BindingExpression:Path=MyCommand; DataItem=null; target element is 'MenuItem' (Name=''); target property is 'Command' (type 'ICommand')
为什么呢?以及如何解决这个问题?使用的DataContext
是不是一种选择,因为一路下跌时的可视化树所在的DataContext已经包含正在显示的实际数据这一问题。我已经尝试过使用 {的RelativeSource FindAncestor,...}
代替,但能产生类似的错误消息。
Why? And how do I fix this? Using the DataContext
is not an option, since this problem occurs way down the visual tree where the DataContext already contains the actual data being displayed. I already tried using {RelativeSource FindAncestor, ...}
instead, but that yields a similar error message.
推荐答案
请参阅的从贾斯汀·泰勒这个文章的解决方法。
See this article from Justin Taylor for a workaround.
更新结果
可悲的是,所引用的博客是没有更多可用。我试图解释程序在另一个SO-答案。可以发现<一href=\"http://stackoverflow.com/questions/3668654/relativesource-binding-from-a-tooltip-or-contextmenu\">here.
这篇关于WPF:绑定文本菜单到MVVM命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!