Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF: KeyBinding for Tab, Swallows Tab and Doesn't Pass It Along

I've got a textbox where I have this: <KeyBinding Command="{Binding MyCommand}" Key="Tab"/>

Problem is it swallows the Tab and doesn't tab to the next control. How can I trap the Tab for the textbox and still preserve tabbing to the next control in the tab order? Edit: I'm also using MVVM and MyCommand is in the ViewModel code, so that's where I need to re-throw the Tab.

like image 376
mike Avatar asked Nov 14 '22 08:11

mike


1 Answers

It's easy to achieve, just don't use KeyBinding for this. Handle your TextBox's OnKeyDown event:

<TextBox KeyDown="UIElement_OnKeyDown" ...

Then on the code-behind, execute your command whenever Tab is pressed. Unlike KeyBinding, this won't swallow the TextInput event so it should work.

    private void OnKeyDown(object sender, KeyEventArgs e)
    {
        switch (e.Key)
        {
            case Key.Tab:
                // Execute your command. Something similar to:
                ((YourDataContextType)DataContext).MyCommand.Execute(parameter:null);
                break;
        }
    }
like image 51
daniloquio Avatar answered Dec 20 '22 03:12

daniloquio