我创建了一个小OKCancelControl
,我想在用户按Enter
或Escape
时绑定(bind)命令
这是 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 和 Escape 的“确定”和“取消”按钮是 Windows 长期以来的标准化内容,因此有一个内置的解决方案。您不需要为命令单独的键绑定(bind),因为您可以将按钮设置为尊重这些键。
要使 WPF 按钮在按 Enter 时“按下”,请在按钮的 Xaml 中设置 IsDefault="True"
。同样,设置 IsCancel="True"
将导致在您按 Esc 键时按下按钮。
无论控件的焦点如何,这两个键都应该可以在事件窗口中的任何位置工作。值得注意的是,如果您的窗口中有多个“默认”或“取消”按钮,则行为可能是不可预测的。
关于c# - 如何将 UserControl 的 KeyBinding 传递给其父控件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11053945/