7

I have an application where I have a UserControl with a toolbar in it. This toolbar has a button Execute which in turn has its command bound to an ICommand derived class that the viewmodel exposes as a property.

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

Now, I'd like to bind this to a keyboard shortcut (F5) as well. This needs to be bound in the context of the UserControl since, it's only applicable if this usercontrol is visible at the moment.

Another option is to bind it to the KeyDown of the textbox that actually contains the text to execute, but I'm really shaky when it comes to how to route the event from the control to the command in the viewmodel without really ugly hacks in the code-behind of the usercontrol.

Any pointers are appreciated!

user7116
  • 63,008
  • 17
  • 141
  • 172
Dervall
  • 5,736
  • 3
  • 25
  • 48
  • possible duplicate of [Keyboard shortcuts in WPF](http://stackoverflow.com/questions/1361350/keyboard-shortcuts-in-wpf) – Daniel Hilgarth Apr 18 '12 at 12:38
  • 1
    It's along the same lines, but it's not really the same question. That talks about how to bind standard commands, while this binds a custom command to a property in the view models. The solution turned out to be similar but still, different things. – Dervall Apr 18 '12 at 12:45
  • @DanielHilgarth: yeah I don't think its a duplicate, or at least the solution provided in the other question is poor (it's the WinForms solution to a MVVM problem). – user7116 Apr 18 '12 at 13:07
  • @sixlettervariables: I don't see any winforms in the question or answer – Daniel Hilgarth Apr 18 '12 at 13:08
  • @DanielHilgarth: I meant WinForms as an adjective to meaning *low quality* or *not helpful* for WPF/MVVM. – user7116 Apr 18 '12 at 13:10

2 Answers2

25

There was another answer that disappeared for some reason. This worked fine:

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

I'd like to give credit to that guy if possible. Please appear again :)

Dervall
  • 5,736
  • 3
  • 25
  • 48
2

Afaik, there isn't a way to directly bind to a keypress, but there are some work arounds. It looks like others have had this problem as well, have you seen this post? My other suggestion is to look into attached commands.

Community
  • 1
  • 1
Dan Busha
  • 3,723
  • 28
  • 36