UWP 中是否有 WPF "KeyBinding" 的替代方案?

Is there an alternative to WPF's "KeyBinding" in UWP?

在我的 WPF 应用程序中,我使用下面编写的内容将 F10 键的按键绑定到 运行 我脚本中名为 'btn_font_click' 的方法。然而,显然 UWP 在 XAML 中不支持像这样的直接键绑定,因为它是通用的而不是为 Windows 设计的。

有什么方法可以在 UWP 应用程序中获得同样的效果?

<Window.Resources>
     <RoutedUICommand x:Key="cmd1"></RoutedUICommand>
</Window.Resources>
<Window.CommandBindings>
     <CommandBinding Command="{StaticResource cmd1}" 
     Executed="btn_font_Click"> 
     </CommandBinding>
</Window.CommandBindings>
<Window.InputBindings>
     <KeyBinding  Key="F10" Command="{StaticResource cmd1}"></KeyBinding>
</Window.InputBindings>

我正在使用 RFID reader 输入数据。目前,当扫描 RFID 卡时,它会按 F10,输入数据,然后按回车键。 我的想法是 F10 将键盘焦点设置到一个文本框,然后脚本等待输入键,同时 RFID 键入其数据,然后它获取文本框中的内容并将其拆分为一个数组以供在应用程序中使用。

如果有更好或更直接的方法将数据从 RFID 卡中获取到我的阵列,我愿意接受其他可能的解决方案。

编辑:经过一段时间的研究后,我发现 'Keyboard Accelerator' 最适合该程序的当前功能,因为我希望 RFID 卡在应用程序未运行时仍能正常工作重点。我可以得到一些关于如何设置键盘加速器将 F10 按键链接到 运行 我的方法的指示吗?

如果您想设置这种应用程序范围的键盘快捷键机制,激活器绝对是一种实现方式。

有一个 documentation on keyboard accelerators available and this functionality is available since the Fall Creators Update. Each UIElement has a KeyboardAccelerators collection,它允许您定义与之交互的键盘快捷键。如果按钮和菜单项调用指定的快捷方式会自动调用控件,但要使您的 TextBox 聚焦,您必须使用 Invoked 事件自行指定此行为:

<TextBox>
    <TextBox.KeyboardAccelerators>                
            <KeyboardAccelerator Modifiers="None"                       
                Key="F10" Invoked="KeyboardAccelerator_OnInvoked" />
    </TextBox.KeyboardAccelerators>
</TextBox>

然后在事件处理程序中 TextBox 被聚焦:

private void KeyboardAccelerator_OnInvoked(
      KeyboardAccelerator sender, 
      KeyboardAcceleratorInvokedEventArgs args )
{
    (args.Element as Control).Focus(FocusState.Keyboard);
}

KeyboardAcceleratorInvokedEventArgs.Element 属性 包含对我们 TextBox 的引用,我将其转换为 Control,因为这是 TextBox 的父级声明Focus 方法,您可以在任何可聚焦控件上重复使用此方法。