2015-04-23 109 views
2

我试图用键盘快捷键为WPF菜单项

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

到键盘快捷键在我的XAML代码添加到菜单项与按Ctrl + Ø

但它无法正常工作 - 它不会调用Click选项。

有没有解决方案?

+0

http://stackoverflow.com/questions/4682915/defining-menuitem-shortcuts –

回答

5

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

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

你可以做的是与分配的输入手势的窗口

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) 
     })); 

    //... 
} 

创建RoutedUICommand,然后在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> 
+0

谢谢,这真的工作 – keerthee

1

你应该以这种方式取得成功: Defining MenuItem Shortcuts 通过使用键绑定:

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

我不想一个内置命令,但我自己 – keerthee