Jackson Dean Goodwin
Jackson Dean Goodwin

Reputation: 625

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.

Upvotes: 11

Views: 36737

Answers (3)

SnakE
SnakE

Reputation: 2571

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.

Upvotes: 0

user2024396
user2024396

Reputation: 1

for binding cross visual tree, refer to

Binding Visibility for DataGridColumn in WPF

or jsut try search BindingProxy

Upvotes: -1

LPL
LPL

Reputation: 17063

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

Upvotes: 11

Related Questions