简体   繁体   中英

How to bind a Command to a MenuItem in C# WPF

I've been reading posts for most of the day and can't find this or figure it out. Pretty much all the questions and answers build the menu in XAML but I'm trying do this in code.

The menu builds fine (there's more to it, just abbreviated here) and enables or disables properly but I can't get the command to execute. There is a button on the menu ribbon that resubmits fine so I know the code on the back end works I just can't seem to figure out how to invoke it from the menu. Any ideas would be nice.

Mouse event to build and display menu from MainView.xaml.cs. There are **'s on the line that needs fixed.

private void MainDataGrid_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
    ContextMenu m = new ContextMenu();
    MenuItem mi = new MenuItem();

    m.Items.Add(new MenuItem());
    mi = (MenuItem)m.Items[0];
    mi.Header = "Resubmit";
    **mi.CommandBindings.Add(new CommandBinding(ApplicationCommands.New, ResubmitCommand));**
    mi.IsEnabled = MainViewModel.CurrentSelectedItems.Count > 0;
    .
    .
    .
    m.IsOpen = true;
}

The ResubmitCommand from my MainViewModel.cs:

public ICommand ResubmitCommand
{
    get
    {
        return _resubmitCommand ??
        (_resubmitCommand = new RelayCommand(
        o => Resubmit(),
        o => CanResubmit));
    }
}

Thanks.

You can just set the menu item's Command property:

mi.Command = ResubmitCommand;

By default, ApplicationCommands.New only supports the Ctrl+N input gesture and is usually bound to the main window. You can bind it to a left-click on the menu item:

mi.CommandBindings.Add(new CommandBinding(ApplicationCommands.New,Resubmit));

var leftClickGesture= new MouseGesture(MouseAction.LeftClick);
mi.InputBindings.Add(new InputBinding(ApplicationCommands.New, leftClickGesture));

The lines:

m.Items.Add(new MenuItem());
mi = (MenuItem)m.Items[0];

should be changed to just:

m.Items.Add(mi);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM