Can't wrap my head around implementing KeyBindings
-
18-09-2019 - |
Question
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!
Solution
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.
OTHER TIPS
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!