WPF:将ContextMenu绑定到MVVM命令 [英] WPF: Binding a ContextMenu to an MVVM Command

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

问题描述

假设我有一个窗口,返回一个命令的属性(实际上,它是一个在ViewModel类中使用Command的UserControl,但让我们尽可能简单地重现问题)。



以下作品:

 < 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,...} ,但是会产生类似的错误消息。

解决方案

请参阅

更新

很遗憾,引用的博客是没有更多的可用。我试图在另一个SO答案中解释这一进程。可以在
这里找到。


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:

<Window x:Class="Window1" ... x:Name="myWindow">
    <Menu>
        <MenuItem Command="{Binding MyCommand, ElementName=myWindow}" Header="Test" />
    </Menu>
</Window>

But the following does not work.

<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 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 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.

Update
Sadly, the referenced blog is no more available. I have tried to explain the proceeding in another SO-answer. It can be found here.

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

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