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

萝らか妹 提交于 2019-11-30 17:32:10

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

}

Using PreviewKeyDown is exactly what you should do... the "PreviewXYZ" events are fired from the bottom up (so the Window gets it first, then the control)... that lets you do whatever you wanted to do globaly on the "Window" level.

Then, you can choose to say "IsHandled = true" which would prevent it from going to the next control (as far as you are concerned), but you don't have to do this. If you want the event to bubble, then just add your code and leave "IsHandled" to false.

Unfortunately in WPF some controls have some keyboard processing hardcoded internally. The PreviewKeyDown handler in the main window is the answer to

How can I define a keyboard shortcut that works everywhere in the main window

question. And yes, it does mean that you may want to choose switch/case on the key events in the PreviewKeyDown manually...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!