KeyTrigger
这个触发器会在监听到键盘按键事件,并且按下的键与指定条件匹配时,执行一些动作。它适合将快捷键、确认键以及其他键盘交互直接声明在 XAML 中,而不需要在窗口或控件的后台代码中手动订阅键盘事件。
基本用法
<Window x:Class="WpfApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:i="http://schemas.microsoft.com/xaml/behaviors">
<Grid>
<TextBox Width="240"
HorizontalAlignment="Center"
VerticalAlignment="Center">
<i:Interaction.Triggers>
<i:KeyTrigger Key="Enter">
<i:InvokeCommandAction Command="{Binding SubmitCommand}" />
</i:KeyTrigger>
</i:Interaction.Triggers>
</TextBox>
</Grid>
</Window>上面的示例中,当 TextBox 处于键盘焦点并按下 Enter 键时,行为库会执行 SubmitCommand。
指定修饰键
可以通过 Modifiers 属性要求按键组合中包含指定的修饰键。多个修饰键使用逗号分隔:
<TextBox>
<i:Interaction.Triggers>
<i:KeyTrigger Key="S" Modifiers="Control">
<i:InvokeCommandAction Command="{Binding SaveCommand}" />
</i:KeyTrigger>
<i:KeyTrigger Key="S" Modifiers="Control,Shift">
<i:InvokeCommandAction Command="{Binding SaveAsCommand}" />
</i:KeyTrigger>
</i:Interaction.Triggers>
</TextBox>常用的修饰键包括:
ControlAltShiftWindows
例如,Key="S" Modifiers="Control" 表示 Ctrl+S,Key="S" Modifiers="Control,Shift" 表示 Ctrl+Shift+S。
其他配置
除了上面提到的 Key 和 Modifiers,KeyTrigger 还提供了两个其他配置属性:
-
ActiveOnFocus用于控制触发器的监听范围:True:只监听触发器的源元素。False:监听源元素所在根元素上的键盘事件。默认值为False。
-
FiredOn用于指定在按键按下还是释放时触发,类型为KeyTriggerFiredOn:KeyDown:按下按键时触发,默认值。KeyUp:释放按键时触发。
与 WPF 原生键盘绑定的区别
WPF 原生的 KeyBinding 更适合将快捷键绑定到命令:
<Window.InputBindings>
<KeyBinding Key="S"
Modifiers="Control"
Command="{Binding SaveCommand}" />
</Window.InputBindings>而 KeyTrigger 更适合需要在按键后执行一个或多个行为动作的场景:
<TextBox>
<i:Interaction.Triggers>
<i:KeyTrigger Key="S" Modifiers="Control">
<i:InvokeCommandAction Command="{Binding SaveCommand}" />
</i:KeyTrigger>
</i:Interaction.Triggers>
</TextBox>两者的主要区别如下:
| 特性 | KeyTrigger | KeyBinding |
|---|---|---|
| 声明位置 | Interaction.Triggers | InputBindings |
| 执行内容 | 一个或多个 TriggerAction | 一个 ICommand |
| 是否适合直接修改控件 | 可以配合 ChangePropertyAction | 通常需要命令处理 |
| 是否依赖键盘焦点 | 依赖关联元素及其事件路由 | 依赖 WPF 命令路由 |
如果需求只是“按下快捷键执行命令”,优先考虑 KeyBinding;如果需求是“按下按键后组合执行多个行为”,则可以使用 KeyTrigger。