Use EventTrigger on a specific key

lost_bits1110 picture lost_bits1110 · Oct 17, 2011 · Viewed 15.7k times · Source

I would like to invoke a command using EventTrigger when a particular key is touched (for example, the spacebar key)

Currently I have:

  <i:Interaction.Triggers>
       <i:EventTrigger EventName="KeyDown">
            <i:InvokeCommandAction Command="{Binding DoCommand}" CommandParameter="{BindingText}"/>
       </i:EventTrigger>
  </i:Interaction.Triggers>

Now how can I specify that this should occur only when the KeyDown occurs with the spacebar?

Answer

CodeNaked picture CodeNaked · Oct 17, 2011

You would have to build a custom Trigger to handle that:

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);
    }
}