C# 如何向菜单项添加快捷键?

C# 如何向菜单项添加快捷键?,c#,wpf,xaml,menuitem,C#,Wpf,Xaml,Menuitem,我想在按下Alt+N时调用OnNewProjectButton_单击。不幸的是,上面的代码不起作用,因为只有在菜单展开(即具有焦点)时才会调用处理程序。您可以使用它,因为它已经提供了该功能。默认设置非常酷。即使您决定不使用默认的命令模型,第二个链接也应该向您展示如何连接所需的输入手势 编辑:下面是一个示例实现 <MenuItem x:Name="newProjectButton" Click="OnNewProjectButton_Click" Header="_New Project"&

我想在按下Alt+N时调用OnNewProjectButton_单击。不幸的是,上面的代码不起作用,因为只有在菜单展开(即具有焦点)时才会调用处理程序。

您可以使用它,因为它已经提供了该功能。默认设置非常酷。即使您决定不使用默认的命令模型,第二个链接也应该向您展示如何连接所需的输入手势

编辑:下面是一个示例实现

<MenuItem x:Name="newProjectButton" Click="OnNewProjectButton_Click" Header="_New Project">
</MenuItem>
要在菜单项上设置,请参见

    private void NewApplicationCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
    {
        // Whatever logic you use to determine whether or not your
        // command is enabled.  I'm setting it to true for now so 
        // the command will always be enabled.
        e.CanExecute = true;
    }

    private void NewApplicationCommand_Executed(object sender, ExecutedRoutedEventArgs e)
    {
        Console.WriteLine("New command executed");
    }

但与WinForms不同的是

请考虑使用WPF,因为它们会自动为您这样做。我发现它能盖好这口井

    private void NewApplicationCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
    {
        // Whatever logic you use to determine whether or not your
        // command is enabled.  I'm setting it to true for now so 
        // the command will always be enabled.
        e.CanExecute = true;
    }

    private void NewApplicationCommand_Executed(object sender, ExecutedRoutedEventArgs e)
    {
        Console.WriteLine("New command executed");
    }
<MenuItem Header="Paste" 
 ToolTip="Paste the selected text to text box" 
 InputGestureText="Ctrl+V" />