WPF:将ContextMenu绑定到MVVM命令 [英] WPF: Binding a ContextMenu to an MVVM Command
问题描述
以下作品:
< 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>
我收到的错误消息是
System.Windows.Data错误:4:找不到引用ElementName = myWindow的绑定源。 BindingExpression:Path = MyCommand; DataItem = null; target元素是'MenuItem'(Name ='');目标属性为'Command'(类型'ICommand')
为什么?我该如何解决这个问题?使用 DataContext
不是一个选项,因为这个问题发生在视觉树下,DataContext已经包含正在显示的实际数据。我已经尝试使用 {RelativeSource FindAncestor,...}
,但是会产生类似的错误消息。
请参阅 更新 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). The following works: But the following does not work. The error message I get is 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') Why? And how do I fix this? Using the See this article from Justin Taylor for a workaround. Update 这篇关于WPF:将ContextMenu绑定到MVVM命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
很遗憾,引用的博客是没有更多的可用。我试图在另一个SO答案中解释这一进程。可以在这里找到。<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>
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.
Sadly, the referenced blog is no more available. I have tried to explain the proceeding in another SO-answer. It can be found here.