如何将命令绑定到MenuItem(WPF)? [英] How do you bind a command to a MenuItem (WPF)?

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

问题描述

这是我的View.xaml.cs代码:

Here is my code from the View.xaml.cs:

private RelayCommand _closeCommand;
public ICommand CloseCommand
{
    get
    {
        if (_closeCommand == null)
        {
            _closeCommand = new RelayCommand(param => this.OnClose());
        }
        return _closeCommand;
    }
}

public void OnClose()
{
    Close();
}

这里是我的View.xaml中的一些代码:

And here is some code from my View.xaml:

<Window.ContextMenu>
    <ContextMenu>
        <MenuItem Name="menuItem_Close" Header="Close" Command="{Binding CloseCommand}" />
    </ContextMenu> 
</Window.ContextMenu>

当我运行程序并选择关闭菜单项时,没有任何反应。 CloseCommand代码甚至不会被执行。

When I run the program and select the close menu item, nothing happens. The CloseCommand code doesn't even get executed.

推荐答案

ContextMenu 不是VisualTree的一部分,这就是为什么不会继承 DataContext 的原因。这里 ContextMenu。 PlacementTarget 是某种继电器来获取窗口

ContextMenu is not part of the VisualTree, that's why the DataContext will not be inherited. Here ContextMenu.PlacementTarget is some kind of relay to get the Window:

<MenuItem Name="menuItem_Close" Header="Close"
          Command="{Binding Path=PlacementTarget.DataContext.CloseCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}" />

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

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