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?
You would have to build a custom Trigger to handle that:
Another approach would be to use KeyBindings and bind them to your Window, UserControl, FrameworkElement, etc. That will not Trigger a button, but say you have a command "MyCommand" that is called from the button, you could invoke the command from InputBindings.
You could also bind these KeyBindings to a TextBox.
I like the idea with a custom trigger but I didn't managed to make it work (some methods were changed or deprecated therefore the showed above definition of the
SpaceKeyDownEventTrigger
is not compiled now). So, I put here the working version with customRoutedEvent
instead. TheSpaceKeyDownEvent
is defined inMyControl
custom control and is raised from theOnKeyDown
method when an unhandledKeyDown
attached event reachesMyControl
and the key pressed is the spacebar.The
MyControl
could be added to the template of another control, allowing the latter to useEventTrigger
with theSpaceKeyDown
routed event: