views:

373

answers:

2

Hi,

I want to handle hotkeys in my application. Writing a keybinding requires a command, which is fine, but it's not clear to me what is the minimum amount of work needed to implement that command. All the examples I seem to find are over-engineered, unclear or assume I'm using the MVVM pattern which I am not.

So what are the basics to getting a keybinding to work?

Thanks!

A: 

The easiest way to make a Keybinding I know of is doing something like this

in XAML

  <Window.CommandBindings>
    <CommandBinding Command="MyCommand" 
       CanExecute="MyCommandCanExecute"
       Executed="MyCommandExecuted" />
  </Window.CommandBindings>
  <Window.InputBindings>
    <KeyBinding Command="MyCommand" Key="M" Modifiers="Ctrl"/>
  </Window.InputBindings>

in code behind

private void MyCommandCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
  e.CanExecute = true;
  e.Handled = true;
}

private void MyCommandExecuted(object sender, ExecutedRoutedEventArgs e)
{
  MessageBox.Show("Executed!");
  e.Handled = true;
}

It's pretty readable in my opinion, but if you have any questions leave a comment!

Jab
Hi Jab! Is the command binding really neceasary? What if I don't need a canexecute? What about routed command? I don't need to declare one somehow?
Steve the Plant
The missing piece of information you have is that the keybinding causes the command to be "Raised", but not what to do when it is raised. The command will then travel up the UI tree until it encounters a CommandBinding that says what to do when a command message has been intercepted. That's it :)
Anderson Imes
+1  A: 

The minimum amount of work needed to implement a command is simply a class that implements ICommand. RoutedCommand is a simplistic implementation that provides the basic functionality.

Once you have that command set up, the KeyBinding is quite simple. You simply provide a Key, and optional Modifiers for that key. A number of common commands have been included in .NET. For example, you can bind the Copy command to Ctrl+C using this mark-up:

<Window.InputBindings>
 <KeyBinding Command="ApplicationCommands.Copy" Key="C" Modifiers="Ctrl"/>
</Window.InputBindings>

You can check out ApplicationCommands, ComponentCommands, and NavigationCommands for some other built-in commands.

Charlie