Keyboard shortcut for wpf menu item

时间:2015-04-23 05:40:20

标签: c# wpf keyboard-shortcuts menuitem

I am trying to add a keyboard shortcut to the menu item in my xaml code using

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

with Ctrl+O

But it is not working - it is not calling the Click option.

Are there any solutions for this?

2 个答案:

答案 0 :(得分:6)

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>

答案 1 :(得分:1)

你应该以这种方式取得成功: 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>