在特定键上使用 EventTrigger
我想在触摸特定键(例如空格键)时使用 EventTrigger 调用命令
目前我有:
<i:Interaction.Triggers>
<i:EventTrigger EventName="KeyDown">
<i:InvokeCommandAction Command="{Binding DoCommand}" CommandParameter="{BindingText}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
现在如何指定仅当 KeyDown 与空格键同时发生时才发生这种情况?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您必须构建一个自定义触发器来处理该问题:
You would have to build a custom Trigger to handle that:
另一种方法是使用 KeyBindings 并将它们绑定到您的 Window、UserControl、FrameworkElement 等。这不会触发按钮,但假设您有一个从按钮调用的命令“MyCommand”,您可以从 InputBindings 调用该命令。
您还可以将这些 KeyBindings 绑定到 TextBox。
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.
我喜欢使用自定义触发器的想法,但我没有设法使其工作(某些方法已更改或弃用,因此上面显示的
SpaceKeyDownEventTrigger
定义现在尚未编译)。因此,我将带有自定义 RoutedEvent 的工作版本放在这里。SpaceKeyDownEvent
在MyControl
自定义控件中定义,当未处理的KeyDown
附加事件到达时,从OnKeyDown
方法引发MyControl
并且按下的键是空格键。可以将
MyControl
添加到另一个控件的模板中,允许后者将EventTrigger
与SpaceKeyDown
路由事件一起使用: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: