Keyboard shortcuts in WPF
I know about using _
instead of &
, but I'm looking at all the Ctrl + type shortcuts.
Ctrl+Z for undo, Ctrl+S for save, etc.
Is there a 'standard' way for implementing these in WPF applications? Or is it a case of roll your own and wire them up to whatever command/control?
One way is to add your shortcut keys to the commands themselves them as InputGestures
. Commands are implemented as RoutedCommands
.
This enables the shortcut keys to work even if they're not hooked up to any controls. And since menu items understand keyboard gestures, they'll automatically display your shortcut key in the menu items text, if you hook that command up to your menu item.
Steps
-
Create static attribute to hold a command (preferably as a property in a static class you create for commands - but for a simple example, just using a static attribute in window.cs):
public static RoutedCommand MyCommand = new RoutedCommand();
-
Add the shortcut key(s) that should invoke method:
MyCommand.InputGestures.Add(new KeyGesture(Key.S, ModifierKeys.Control));
-
Create a command binding that points to your method to call on execute. Put these in the command bindings for the UI element under which it should work for (e.g., the window) and the method:
<Window.CommandBindings> <CommandBinding Command="{x:Static local:MyWindow.MyCommand}" Executed="MyCommandExecuted"/> </Window.CommandBindings> private void MyCommandExecuted(object sender, ExecutedRoutedEventArgs e) { ... }
I found this to be exactly what I was looking for related to key binding in WPF:
<Window.InputBindings>
<KeyBinding Modifiers="Control"
Key="N"
Command="{Binding CreateCustomerCommand}" />
</Window.InputBindings>
See blog post MVVM CommandReference and KeyBinding
Try this.
First create a RoutedCommand object:
RoutedCommand newCmd = new RoutedCommand();
newCmd.InputGestures.Add(new KeyGesture(Key.N, ModifierKeys.Control));
CommandBindings.Add(new CommandBinding(newCmd, btnNew_Click));