tags:

views:

36

answers:

1

i currently use the onKeyDown event and an if else statement to create keyboard short cuts.

if ((Keyboard.Modifiers & ModifierKeys.Shift) == ModifierKeys.Shift && e.Key == Key.Tab) {

} else if (e.Key == Key.Tab) {

} ...

but if i have quite a few more keyboard short cuts, this gets messy. is there a better implementation?

+3  A: 

You should look at implementing <CommandBindings> and <InputBindings>:

<Window.CommandBindings>
    <CommandBinding Command="Settings" CanExecute="SettingsCanExecute" Executed="SettingsExecuted" />
</Window.CommandBindings>

<Window.InputBindings>
    <KeyBinding Command="Settings" Key="S" Modifiers="Alt" />
</Window.InputBindings>

Your <Button> then becomes:

<Button Height="50" Width="50" Margin="50,5,0,0" Command="Settings" />

The SettingsCanExecute method determines when the button is enabled and the SettingsExecuted method is called when the button is pressed or the key combination struck.

You then don't need the KeyDown handler.

There's a full tutorial on Switch On The Code.

More information on CommandBindings and InputBindings can be found on the MSDN.

ChrisF
wow, this is just what i needed!
jiewmeng
hmm... when i tried `<CommandBinding Command="Preview" CanExecute ...` i get an error on `Command="Preview"` saying cannot convert "Preview". i am using the RibbonWindow instead of Window. does it make a difference? since RibbonWindow extends Window?
jiewmeng
@jiewmeng - don't know. Does it work with a command other than "Preview"? I followed the tutorial in the first instance so I know that it should work.
ChrisF
i am not sure if i missed anything in the tutorial. but looking at the demo code from [John Smith On WPF: Understanding Routed Commands](http://joshsmithonwpf.wordpress.com/2008/03/18/understanding-routed-commands/) i think i need to create a Property on a class then reference it in code... [Snipplr Code Snipplet](http://snipplr.com/view/39602/cwpf-routed-commands/)
jiewmeng