问题
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?
回答1:
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>
回答2:
Found the answer:
<Interactivity:Interaction.Triggers>
<Interactivity:EventTrigger EventName="PreviewKeyDown" >
<command:EventToCommand Command="{Binding ChangeIdCommand}" PassEventArgsToCommand="True" />
</Interactivity:EventTrigger>
</Interactivity:Interaction.Triggers>
来源:https://stackoverflow.com/questions/38433234/bind-any-key-pressed-to-command-in-vm-wpf