views:

3143

answers:

2

I know about using _ instead of &, what I'm looking at is 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?

+7  A: 

Hey Benjol,

It depends on where you want to use those. TextBoxBase derived controls already implement those shortcuts. If you want to use custom keyboard shortcuts you should take a look on Commands and Input gestures. Here is small tutorial form Switch on the Code: WPF Tutorial - Command Bindings and Custom Commands

Hope this helps.

Anvaka
+12  A: 

I understand the standard way is by creating Commands and then adding your shortcut keys to them as InputGestures. 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.

A. Create static attribute to hold command (preferably as property in static class you create for commands - but for simple example, just using static attribute in window .cs):

public static RoutedCommand MyCommand = new RoutedCommand( );

B. Add the shortcut key(s) that should invoke method:

MyCommand.InputGestures.Add( new KeyGesture( Key.S , ModifierKeys.Control ));

C. Create 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) & the method:

<Window.CommandBindings>
    <CommandBinding Command="{x:Static local:MyWindow.MyCommand}" Executed="MyCommandExecuted"/>
</Window.CommandBindings>

private void MyCommandExecuted( object sender, ExecutedRoutedEventArgs e ) { ... }
Abby Fichtner
Thanks, and welcome!
Benjol
glad I could help - am still learning WPF, but I'd just been looking into that very thing. hah, guess this site can be a good way to learn. And thanks!
Abby Fichtner