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

30,679

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}}" />
Share:
30,679
Jackson Dean Goodwin
Author by

Jackson Dean Goodwin

Updated on July 29, 2022

Comments

  • Jackson Dean Goodwin
    Jackson Dean Goodwin almost 2 years

    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.

  • McGarnagle
    McGarnagle over 11 years
    Are you sure it doesn't get the DataContext? In my test it seems to be inheriting the DataContext as you would expect ...
  • Jackson Dean Goodwin
    Jackson Dean Goodwin over 11 years
    I tried your code for the Command="..." but it did not work - just as before - nothing happed.
  • LPL
    LPL over 11 years
    @dbaseman According to this Popup creates its own visualtree. This means no DataContext inheritance for ContextMenu which is placed in a Popup.
  • LPL
    LPL over 11 years
    @JacksonDeanGoodwin Any binding errors? Are you sure that DataContext is set for Window? Maybe try a Button with your Command binding in Window directly for that.
  • Agent007
    Agent007 over 10 years
    Thanks for this. How should I bind a static ICommand to a MenuItem not using a ViewModel binding? I am currently using (which is not working) Command="{x:Static ...}" but that doesn't seem to work with the solution you have provided here. Please help.