Search code examples
c#wpfkey-bindings

Can't wrap my head around implementing KeyBindings


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.