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

后端 未结 3 1311
清酒与你
清酒与你 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:19

    One solution that doesn't involve commands and bindings is to override the owning Window's OnKeyDown method and search a menu item that has a KeyGesture that matches the keyboard event.

    Here is the code for the Window's OnKeyDown override:

    protected override void OnKeyDown(KeyEventArgs e)
    {
        base.OnKeyDown(e);
    
        // here I suppose the window's menu is named "MainMenu"
        MainMenu.RaiseMenuItemClickOnKeyGesture(e);
    }
    

    And here is the utility code that matches a menu item with the keyboard event:

        public static void RaiseMenuItemClickOnKeyGesture(this ItemsControl control, KeyEventArgs args) => RaiseMenuItemClickOnKeyGesture(control, args, true);
        public static void RaiseMenuItemClickOnKeyGesture(this ItemsControl control, KeyEventArgs args, bool throwOnError)
        {
            if (args == null)
                throw new ArgumentNullException(nameof(args));
    
            if (control == null)
                return;
    
            var kgc = new KeyGestureConverter();
            foreach (var item in control.Items.OfType())
            {
                if (!string.IsNullOrWhiteSpace(item.InputGestureText))
                {
                    KeyGesture gesture = null;
                    if (throwOnError)
                    {
                        gesture = kgc.ConvertFrom(item.InputGestureText) as KeyGesture;
                    }
                    else
                    {
                        try
                        {
                            gesture = kgc.ConvertFrom(item.InputGestureText) as KeyGesture;
                        }
                        catch
                        {
                        }
                    }
    
                    if (gesture != null && gesture.Matches(null, args))
                    {
                        item.RaiseEvent(new RoutedEventArgs(MenuItem.ClickEvent));
                        args.Handled = true;
                        return;
                    }
                }
    
                RaiseMenuItemClickOnKeyGesture(item, args, throwOnError);
                if (args.Handled)
                    return;
            }
        }
    

提交回复
热议问题