Bind any key pressed to command in VM WPF

人走茶凉 提交于 2019-12-12 10:37:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!