Associating a keyboard shortcut with a command in a view model in WPF

I have an application in which I have a UserControl with a toolbar. This toolbar has an Execute button, which in turn has its own command bound to the ICommand derived class, which provides the viewmodel as a property.

 <Button Grid.Row="0" Command="{Binding ExecuteCommand}">Execute</Button> 

Now I would like to snap this to a keyboard shortcut ( F5 ). This needs to be linked in the context of the UserControl , because it only applies if this user control is currently displayed.

Another option is to bind it to a KeyDown text field that actually contains the text to execute, but I'm very shaky when it comes to redirecting an event from a control to a command in view mode without really ugly hacks in the code for user control.

Any pointers are appreciated!

+6
source share
2 answers

There was another answer that somehow disappeared. This works great:

 <UserControl.InputBindings> <KeyBinding Key="F5" Command="{Binding ExecuteCommand}" /> </UserControl.InputBindings> 

I would like to pay tribute to this guy, if possible. Try again:)

+24
source

Afaik, there is no way to directly bind to keys, but there are some problems. It seems that others had this problem too, have you seen this post ? My other suggestion is to look at the attached commands .

+2
source

Source: https://habr.com/ru/post/913522/


All Articles