Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding a WPF ShortCut Key to a Command in the ViewModel

I have a WPF app that is using the MVVM pattern. Hooking up buttons to the VM is pretty straight forward since they implement the ICommand. I have a context menu that works similar. The next step is to create shortcut keys for the context menu. I can't figure out how to get the shortcut key invoke the Command. Here is an example:

<MenuItem Header="Update" Command="{Binding btnUpdate}" >     <MenuItem.Icon>         <Image Source="/Images/Update.png"                Width="16"                Height="16" />         </MenuItem.Icon>     </MenuItem> 

now I've added this:

<Window.InputBindings>     <KeyBinding Key="U"                 Modifiers="Control"                  Command="{Binding btnUpdate}" /> </Window.InputBindings> 

to try and connect the shortcut keys to the same binding, but this doesn't work. The error is:

Error 169 A 'Binding' cannot be set on the 'Command' property of type 'KeyBinding'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject.

Isn't there a way to hook up this event to the Command? I can't figure this out.

thanks in advance!

Bill

like image 364
Bill Campbell Avatar asked Mar 04 '10 21:03

Bill Campbell


People also ask

What is command binding in WPF?

The command is the action to be executed. The command source is the object which invokes the command. The command target is the object that the command is being executed on. The command binding is the object which maps the command logic to the command.

How many ways you can bind a ViewModel with XAML?

There are two ways in which we can bind View and View Model.


1 Answers

The following code can be used to bind a shortcut key directly to a command:

<Window.InputBindings>     <KeyBinding Command="{Binding Path=NameOfYourCommand}"                  Key="O"                  Modifiers="Control"/> </Window.InputBindings> 

Add this after Window.Resources in the XAML code of your view.

like image 166
Michel Keijzers Avatar answered Nov 10 '22 07:11

Michel Keijzers