Keyboard shortcuts in WPF

Benjol picture Benjol · Sep 1, 2009 · Viewed 120.5k times · Source

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?

Answer

Abby Fichtner picture Abby Fichtner · Sep 25, 2009

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.

  1. 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();
    
  2. Add the shortcut key(s) that should invoke method:

     MyCommand.InputGestures.Add(new KeyGesture(Key.S, ModifierKeys.Control));
    
  3. 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) { ... }