c# - 如何将 UserControl 的 KeyBinding 传递给其父控件?

标签 c# wpf xaml mvvm

我创建了一个小OKCancelControl,我想在用户按EnterEscape时绑定(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/

相关文章:

c# - 尝试 UserPrincipal.FindByIdentity 时出现登录失败错误

c# - 在 LINQ 中并行加载图像

c# - 如何在 PDFSharp 中使用私有(private)字体

wpf - WinForms ElementHost 错误

c# - 使用 MVVM 的嵌套动态内容控件

wpf - WindowChrome ResizeBorderThickness 问题

c# - 带有浏览按钮作为用户控件的 WPF 路径文本框

c# - 什么实际处理 Windows 壁纸的绘制?

c# - 检查 XML 元素是否存在

c# - ListPicker SelectionChanged 被多次调用