如何将用户控件的键绑定传递到其父级
本文关键字:绑定 用户 控件 | 更新日期: 2023-09-27 18:37:15
我创建了一个小OKCancelControl
,我想在用户按Enter
或Escape
时绑定命令
下面是 XAML
<UserControl.InputBindings>
<KeyBinding Key="Enter"
Command="{Binding ElementName=this, Path=OkCommand, UpdateSourceTrigger=PropertyChanged}"/>
<KeyBinding Key="Escape"
Command="iw:InnerWindow.CancelCommand"/>
</UserControl.InputBindings>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Border Grid.Column="0"
Style="{StaticResource BorderStyle}">
<Button Content="{Binding ElementName=this, Path=ButtonName, UpdateSourceTrigger=PropertyChanged}"
Command="{Binding ElementName=this, Path=OkCommand, UpdateSourceTrigger=PropertyChanged}"/>
</Border>
<Border Grid.Column="1"
Style="{StaticResource BorderStyle}">
<Button Content="{Binding Source={x:Static Member=t:BaseText.Cancel}}"
Command="iw:InnerWindow.CancelCommand" />
</Border>
</Grid>
但是,只有当我的UserControl
具有对我的情况不好的焦点时,才会处理KeyBinding
。
我想找到一种 MVVM 或 XAML 方法(如果可能的话)让父级"侦听"用户按键。
提前谢谢你;)
使用Enter和Ese的"确定"和"取消"按钮是Windows长期以来标准化的东西,因此有一个内置的解决方案。 命令不需要单独的键绑定,因为可以将按钮设置为遵循这些键。
若要使 WPF 在按回车键时"按下"按钮,请在按钮的 Xaml 中设置IsDefault="True"
。 同样,设置IsCancel="True"
将导致在点击 Escape 时按下按钮。
然后,无论控件的焦点如何,这两个键都应在活动窗口中的任何位置工作。 值得注意的是,如果您的窗口中有多个"默认"或"取消"按钮,则行为可能是不可预测的。