Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 316
Jackson Dean Goodwin Avatar asked Dec 11 '12 18:12

Jackson Dean Goodwin


1 Answers

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}}" />
like image 146
LPL Avatar answered Nov 13 '22 04:11

LPL