How do you bind a command to a MenuItem (WPF)?

喜欢而已 提交于 2019-11-29 08:56:30

问题


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();
}

And here is some code from my View.xaml:

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

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


回答1:


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}}" />



回答2:


Old question, new answer. For me the problem was that GalaSoft.MvvmLight.Command.RelayCommand didn't support closures for the action. RelayCommand stores a weak reference to the action so a closure gets deallocated almost immediately. The action must be a model method or be retained in some other way.




回答3:


for binding cross visual tree, refer to

Binding Visibility for DataGridColumn in WPF

or jsut try search BindingProxy



来源:https://stackoverflow.com/questions/13826504/how-do-you-bind-a-command-to-a-menuitem-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!