Why doesn't setting MenuItem.InputGestureText cause the MenuItem to activate when I perform the input gesture?

后端 未结 3 1318
清酒与你
清酒与你 2021-01-18 14:22

I want to implement Keyboard shortcuts for a MenuItem. I have used the code below:



        
3条回答
  •  日久生厌
    2021-01-18 15:01

    The best way to do this is to make a Command, and associate the InputGesture with that command:

    public static class Commands
    {
        public static readonly RoutedCommand CreateNew = new RoutedCommand("New", typeof(Commands));
    
        static Commands()
        {
            SomeCommand.InputGestures.Add(new KeyGesture(Key.N, ModifierKeys.Control));
        }
    }
    
    ...
    
    // Wherever you want to create the MenuItem. "local" should be the namespace that
    // you delcared "Commands" in.
    
    
    ...
    
    // Wherever you want to process the command. I am assuming you want to do it in your 
    // main window, but you can do it anywhere in the route between your main window and 
    // the menu item.
    
         Executed="CreateNew_Executed" />
    
    
    ...
    
    // In the code behind for your main window (or whichever file you put the above XAML in)
    private void CreateNew(object sender, ExecutedRoutedEventArgs e)
    {
        ...
    }
    

    If you really just want a "New" command, you can skip creating the RoutedCommand and InputGesture, because that command is already created for you:

    
    
    ...
    
    
        
    
    
    ...
    
    private void New_Executed(object sender, ExecutedRoutedEventArgs e)
    {
        ...
    }
    

提交回复
热议问题