在特定键上使用EventTrigger

los*_*110 13 wpf interaction eventtrigger keydown

我想在触摸特定键时使用EventTrigger调用命令(例如,空格键)

目前我有:

  <i:Interaction.Triggers>
       <i:EventTrigger EventName="KeyDown">
            <i:InvokeCommandAction Command="{Binding DoCommand}" CommandParameter="{BindingText}"/>
       </i:EventTrigger>
  </i:Interaction.Triggers>
Run Code Online (Sandbox Code Playgroud)

现在我怎么能指定只有当空格键出现KeyDown时才会出现这种情况?

Cod*_*ked 15

您必须构建一个自定义触发器来处理:

public class SpaceKeyDownEventTrigger : EventTrigger {

    public SpaceKeyDownEventTrigger() : base("KeyDown") {
    }

    protected override void OnEvent(EventArgs eventArgs) {
        var e = eventArgs as KeyEventArgs;
        if (e != null && e.Key == Key.Space)
            this.InvokeActions(eventArgs);
    }
}
Run Code Online (Sandbox Code Playgroud)


kal*_*ohn 12

另一种方法是使用KeyBindings并将它们绑定到Window,UserControl,FrameworkElement等.这不会触发按钮,但是说你有一个从按钮调用的命令"MyCommand",你可以从InputBindings调用命令.

<UserControl.InputBindings>
   <KeyBinding Command="{Binding Path=ApplyCommand}" Key="Enter"/>
   <KeyBinding Command="{Binding Path=NextPage}" Modifiers="Ctrl" Key="Left"/>
</UserControl.InputBindings>

<StackPanel> 
    <Button IsDefault="True" Content="Apply">
        <i:Interaction.Triggers>
           <i:EventTrigger EventName="Click">
               <i:InvokeCommandAction Command="{Binding Path=ApplyCommand}" />                            
           </i:EventTrigger>
        </i:Interaction.Triggers>
    </Button>
 </StackPanel>
Run Code Online (Sandbox Code Playgroud)

您还可以将这些KeyBinding绑定到TextBox.