Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何将UserControl的KeyBinding传递给其父控件?_C#_Wpf_Xaml_Mvvm - Fatal编程技术网

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

C# 如何将UserControl的KeyBinding传递给其父控件?,c#,wpf,xaml,mvvm,C#,Wpf,Xaml,Mvvm,我创建了一个小的OKCancelControl,当用户按Enter或Escape 这是XAML <UserControl.InputBindings> <KeyBinding Key="Enter" Command="{Binding ElementName=this, Path=OkCommand, UpdateSourceTrigger=PropertyChanged}"/> <KeyBinding Key="E

我创建了一个小的
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和Escape的OK和Cancel按钮是Windows长期以来的标准化功能,因此有一个内置的解决方案。命令不需要单独的键绑定,因为您可以设置按钮以尊重这些键

要使WPF按钮在按下enter键时“按下”,请在按钮的Xaml中设置
IsDefault=“True”
。类似地,设置
IsCancel=“True”
将导致在按下Escape时按下按钮

然后,无论控件的焦点如何,这两个键都应在活动窗口中的任何位置工作。值得注意的是,如果您的窗口中有多个默认或取消按钮,则行为可能无法预测