Michael
Michael

Reputation: 2123

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>

Upvotes: 2

Views: 790

Answers (2)

rattler
rattler

Reputation: 389

May be I am a bit late, but:

Automatic shortcut hinting on menu items works with RoutedCommand.

public static readonly RoutedUICommand NewProject = new RoutedUICommand() { InputGestures = { new KeyGesture(Key.N, ModifierKeys.Control) } };

If you do so - you will get your hotkey working (even without input binding in window) and you will see this hotkey in any menu item bound to this command. This will work only with RoutedCommand (type is hardcoded in WPF source). If your command is not RoutedCommand (and it isn't, as you use ICommand pattern) - you have to set gesture hints by your own.

So there are two options: use RoutedCommand and event handlers for them (in UI code!) or implement your own commands and do whatever you can with shortcut hints.

Upvotes: 0

mm8
mm8

Reputation: 169210

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 :)

Upvotes: 2

Related Questions