7

WPF 允许我轻松地将窗口级别的键盘快捷键绑定到使用 InputBindings 属性的方法。WinRT 中的等价物是什么?将键盘快捷键绑定到 WinRT 中的方法的正确方法是什么?

4

2 回答 2

7

此处描述了键盘快捷键。我认为您想要访问键加速键

访问键是应用程序中一段 UI 的快捷方式。访问键由 Alt 键和一个字母键组成。

加速键是应用命令的快捷方式。你的应用可能有也可能没有与命令完全对应的 UI。加速键由 Ctrl 键和一个字母键组成。

以下示例演示了媒体播放、暂停和停止按钮的快捷键的可访问实现:

<MediaElement x:Name="Movie" Source="sample.wmv"
  AutoPlay="False" Width="320" Height="240"/>

<StackPanel Orientation="Horizontal" HorizontalAlignment="Center">

  <Button x:Name="Play" Margin="1,2"
    ToolTipService.ToolTip="shortcut key: Ctrl+P"
    AutomationProperties.AccessKey="Control P">
    <TextBlock><Underline>P</Underline>lay</TextBlock>
  </Button>

  <Button x:Name="Pause" Margin="1,2"
    ToolTipService.ToolTip="shortcut key: Ctrl+A"
    AutomationProperties.AccessKey="Control A">
    <TextBlock>P<Underline>a</Underline>use</TextBlock>
  </Button>

  <Button x:Name="Stop" Margin="1,2"
    ToolTipService.ToolTip="shortcut key: Ctrl+S"
    AutomationProperties.AccessKey="Control S">
    <TextBlock><Underline>S</Underline>top</TextBlock>
  </Button>

</StackPanel>

<object AutomationProperties.AcceleratorKey="ALT+F" />

重要提示:设置 AutomationProperties.AcceleratorKey 或 AutomationProperties.AccessKey 不会启用键盘功能。它只向 UI 自动化框架报告应该使用哪些键,以便这些信息可以通过辅助技术传递给用户。密钥处理的实现仍然需要在代码中完成,而不是 XAML。您仍然需要在相关控件上附加 KeyDown 或 KeyUp 事件的处理程序,以便在您的应用程序中实际实现键盘快捷键行为。此外,访问键的下划线文本装饰不会自动提供。如果您希望在 UI 中显示带下划线的文本,则必须将助记符中特定键的文本显式下划线作为内联下划线格式。

有关代码方面的实现细节,请参阅@Magiel 的答案。

于 2012-08-18T00:27:42.060 回答
5

重要的!!设置 AutomationProperties.AcceleratorKey 或 AutomationProperties.AccessKey 不会启用键盘功能。它只向 UI 自动化框架报告应该使用哪些键,以便这些信息可以通过辅助技术传递给用户。密钥处理的实现仍然需要在代码中完成,而不是 XAML。

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    // Set the input focus to ensure that keyboard events are raised.
    this.Loaded += delegate { this.Focus(FocusState.Programmatic); };
}

private void Grid_KeyUp(object sender, KeyRoutedEventArgs e)
{
    if (e.Key == VirtualKey.Control) isCtrlKeyPressed = false;
}

private void Grid_KeyDown(object sender, KeyRoutedEventArgs e)
{
    if (e.Key == VirtualKey.Control) isCtrlKeyPressed = true;
    else if (isCtrlKeyPressed)
    {
        switch (e.Key)
        {
            case VirtualKey.P: DemoMovie.Play(); break;
            case VirtualKey.A: DemoMovie.Pause(); break;
            case VirtualKey.S: DemoMovie.Stop(); break;
        }
    }
}
于 2013-10-15T17:23:43.207 回答