Bind any key pressed for a command in WPF VM

I am trying to bind any keyboard key to a command in the ViewModel .

I know that I can bind a specific key using:

 <Window.InputBindings> <KeyBinding Command="{Binding ChangeIdCommand}" Key="B"/> </Window.InputBindings> 

Is it possible to bind all keystrokes to ChangeIdCommand without typing them manually?

+5
c # command wpf mvvm key-bindings
Jul 18 '16 at 9:33
source share
2 answers

Try this after defining your window:

 <Window x:Class="wpfApplication.MainWindow" xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" ...> <i:Interaction.Triggers> <i:EventTrigger EventName="KeyDown"> <i:InvokeCommandAction Command="{Binding ChangeIdCommand}" /> </i:EventTrigger> </i:Interaction.Triggers> 
+3
Jul 18 '16 at 9:54 on
source share

Found answer:

 <Interactivity:Interaction.Triggers> <Interactivity:EventTrigger EventName="PreviewKeyDown" > <command:EventToCommand Command="{Binding ChangeIdCommand}" PassEventArgsToCommand="True" /> </Interactivity:EventTrigger> </Interactivity:Interaction.Triggers> 
-one
Jul 18 '16 at 11:11
source share