简体   繁体   中英

Bind a keyboard shortcut to a command in the view model in WPF

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!

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 :)

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM