Bind any key pressed to command in VM WPF
Asked Answered
D

2

8

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?

Deplane answered 18/7, 2016 at 9:33 Comment(0)
N
7

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>
Nissa answered 18/7, 2016 at 9:54 Comment(3)
This is the correct answer. KeyBindings cannot be used to match "any key". (Note: this snippet requires a Reference to System.Windows.Interactivity, and the CommandParameter is optional.)Reisch
@Reisch What's the syntax for CommandParameter in this case? From what I'm reading, passing the EventArgs as a parameter isn't supported out of the box.Woebegone
@JoshNoe: Great question, and I'm afraid I don't know. The syntax for CommandParameter can be seen in the pre-edited version of this answer, but I believe it is only intended for use with passing a property value (the value in an adjacent element, for example) as a parameter to the bound command, not for EventArgs.Reisch
D
-2

Found the answer:

<Interactivity:Interaction.Triggers>
    <Interactivity:EventTrigger EventName="PreviewKeyDown" >
        <command:EventToCommand Command="{Binding ChangeIdCommand}" PassEventArgsToCommand="True" />
    </Interactivity:EventTrigger>
</Interactivity:Interaction.Triggers>
Deplane answered 18/7, 2016 at 11:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.