WPF: How to prevent a control from stealing a key gesture?

后端 未结 3 1852
有刺的猬
有刺的猬 2021-01-04 04:50

In my WPF application I would like to attach an input gesture to a command so that the input gesture is globally available in the main window, no matter which control has th

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-04 04:59

    The following workaround seems to have the desired effect of having the command global to the window; however, I still wonder whether there is no easier way to do this in WPF:

    private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        foreach (InputBinding inputBinding in this.InputBindings)
        {
            KeyGesture keyGesture = inputBinding.Gesture as KeyGesture;
            if (keyGesture != null && keyGesture.Key == e.Key && keyGesture.Modifiers == Keyboard.Modifiers)
            {
                if (inputBinding.Command != null)
                {
                    inputBinding.Command.Execute(0);
                    e.Handled = true;
                }
            }
        }
    
        foreach (CommandBinding cb in this.CommandBindings)
        {
            RoutedCommand command = cb.Command as RoutedCommand;
            if (command != null)
            {
                foreach (InputGesture inputGesture in command.InputGestures)
                {
                    KeyGesture keyGesture = inputGesture as KeyGesture;
                    if (keyGesture != null && keyGesture.Key == e.Key && keyGesture.Modifiers == Keyboard.Modifiers)
                    {
                        command.Execute(0, this);
                        e.Handled = true;
                    }
                }
            }
        }
    }
    

    }

提交回复
热议问题