How do I implement wpf keybinding

1.6k views Asked by At

I want to be able to allow users to change hotkeys at runtime.

Does anyone have a concrete example on how to bind a key in codebehind c# to accomplish this?

I assume I have to do a keybinding with a RoutedCommand. Assume that I want to push a button on the UI with the hotkey.

eg... Let the user push F5 to click the btnGo on the app.

1

There are 1 answers

5
Trevor Elliott On

The way that commands work is a bit different from your thinking. When you press a button it doesn't fire the click for a button in your app. Rather, you define a command (in this case, you could have a command called "Go") and you can assign this command to various elements in your application (menu items, buttons, etc.) All of these items fire the command and the command has an "Executed" function which performs the code.

If you add CommandBindings to your main window then you can use hotkeys to fire those commands globally. You can easily place command bindings in XAML by such code as:

<Window.CommandBindings>
    <CommandBinding Command="local:MyCommands.Go" CanExecute="GoCanExecute" Executed="Go" />
</Window.CommandBindings>

To create your own command you can create a "RoutedUICommand" in code and set the default members (default name, default keybind, etc.). You most likely want to make it a static property of a class.

Then if you want to change or add keybinds for this command you can just access this static property and modify the InputGestures collection. You can clear it, add new key bindings, and change them as necessary.