Idanis
Idanis

Reputation: 1988

Bind any key pressed to command in VM WPF

I'm trying to bind any keyboard key pressed 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>

Can I bind all key presses to ChangeIdCommand without having to type them all manually?

Upvotes: 8

Views: 4491

Answers (2)

Jose
Jose

Reputation: 1897

Try this after your window definition:

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

Upvotes: 7

Idanis
Idanis

Reputation: 1988

Found the answer:

<Interactivity:Interaction.Triggers>
    <Interactivity:EventTrigger EventName="PreviewKeyDown" >
        <command:EventToCommand Command="{Binding ChangeIdCommand}" PassEventArgsToCommand="True" />
    </Interactivity:EventTrigger>
</Interactivity:Interaction.Triggers>

Upvotes: -2

Related Questions