【问题标题】:Keyboard shortcut for wpf menu itemwpf 菜单项的键盘快捷键
【发布时间】:2015-04-23 05:40:19
【问题描述】:

我正在尝试使用在我的 xaml 代码中向菜单项添加键盘快捷方式

<MenuItem x:Name="Options" Header="_Options" InputGestureText="Ctrl+O" Click="Options_Click"/>

Ctrl+O

但它不起作用 - 它没有调用 Click 选项。

有解决办法吗?

【问题讨论】:

标签: c# wpf keyboard-shortcuts menuitem


【解决方案1】:

InputGestureText 只是一个文本。它不会将密钥绑定到MenuItem

此属性不会将输入手势与菜单项相关联;它只是将文本添加到菜单项。应用程序必须处理用户的输入才能执行操作

您可以做的是在您的窗口中创建RoutedUICommand 并指定输入手势

public partial class MainWindow : Window
{
    public static readonly RoutedCommand OptionsCommand = new RoutedUICommand("Options", "OptionsCommand", typeof(MainWindow), new InputGestureCollection(new InputGesture[]
        {
            new KeyGesture(Key.O, ModifierKeys.Control)
        }));

    //...
}

然后在 XAML 中将该命令绑定到针对MenuItem 设置该命令的某个方法。在这种情况下,InputGestureTextHeader 都将从 RoutedUICommand 中提取,因此您无需针对 MenuItem 设置它

<Window.CommandBindings>
    <CommandBinding Command="{x:Static local:MainWindow.OptionsCommand}" Executed="Options_Click"/>
</Window.CommandBindings>
<Menu>
    <!-- -->
    <MenuItem Command="{x:Static local:MainWindow.OptionsCommand}"/>
</Menu>

【讨论】:

    【解决方案2】:

    你应该以这种方式成功: Defining MenuItem Shortcuts 通过使用 KeyBindings:

    <Window.CommandBindings> <CommandBinding Command="New" Executed="CommandBinding_Executed" /> </Window.CommandBindings> <Window.InputBindings> <KeyBinding Key="N" Modifiers="Control" Command="New"/> </Window.InputBindings>
    

    【讨论】:

    • 这仅适用于常用命令,例如新建、打开、剪切、复制、粘贴等。它不适用于自定义用户定义的命令
    猜你喜欢
    • 2010-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-25
    • 1970-01-01
    • 2015-04-18
    • 2016-03-13
    相关资源
    最近更新 更多