Search code examples
c#wpficommand

Binding an ICommand to a MenuItem and assign a ShortCut


I have the following scenario:

A ViewModel with multiple ICommand (RelayCommand) properties. Those properties are bound to menuitems in the view. Some of the menuitems should have a keyboard-shortcut. To do this I've tried using InputBindings of the window. This works - but I have to assign the InputGestureText manually to the MenuItem. So I guess theres a better way to bind a ICommand to a MenuItem and assign a shortcut...

// ViewModel
class MyViewModel: ViewModelBase {
    public ICommand TestCommand {get; set;}
}

// View
<Window...>

    <Window.InputBindings>
        <KeyBinding Command="{Binding TestCommand}" Key="R" Modifiers="Control" />
    </Window.InputBindings>

    // ...
    <MenuItem Name="MenuItemTest" Command="{Binding TestCommand}"
              Header="Test" InputGestureText="Ctrl + R" />

</Window>

Solution

  • The InputGestureText property is just used to set a text that describes an input gesture that will call the command associated to the command.

    It does not associate the input gesture with the menu item somehow; it simply adds text to the menu item. This is documented on MSDN: https://msdn.microsoft.com/en-us/library/system.windows.controls.menuitem.inputgesturetext(v=vs.110).aspx.

    So no, there is no better way of doing what you are doing :)