Search code examples
wpftextboxfocustabcontrolshortcut

WPF blocking InputBindings for shortcut when the focus is on TextBox kind of element


I need tabs in TabControl navigated using Ctrl + PageUp/PageDown - previous/next. Everything works fine, until there is a TextBox control inside of a Tab and there is a focus on it. Then the shortcut won't work. Other key combos work fine, but PageUp and PageDown don't. This is my Tab control:

 <TabControl.InputBindings>
  <KeyBinding Modifiers="Control"
              Key="PageDown"
              Command="{Binding Source={StaticResource ShortCutCommands}, Path=TabControlNextItemCommand}"
              CommandParameter="{Binding ElementName=TabControl}"/>
  <KeyBinding Modifiers="Control"
              Key="PageUp"
              Command="{Binding Source={StaticResource ShortCutCommands}, Path=TabControlPreviousItemCommand}"
              CommandParameter="{Binding ElementName=TabControl}"/>
</TabControl.InputBindings>

Did someone have a similar problem?


Solution

  • I know using commands would be ideal, but if TextBox is eating those key inputs before the KeyBinding has a chance to work, the only solution I know of is to use the PreviewKeyDown event instead of input bindings.

    private void TabControl_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Tab && Keyboard.Modifiers.HasFlag(ModifierKeys.Control))
        {
            //Invoke command here
        }
    }