Hosea146
Hosea146

Reputation: 7722

How to take action on certain keystrokes in TextBox?

I have a WPF window with a text box. I'd like to detect when a user presses either the Enter key or Tab key. When either of these keys are pressed, I'd like to bind to an action in our view model. Could someone show me how this can be done?

Upvotes: 2

Views: 1011

Answers (1)

brunnerh
brunnerh

Reputation: 185489

Handle the KeyDown event.

<TextBox KeyDown="TextBox_KeyDown"/>
private void TextBox_KeyDown(object sender, KeyEventArgs e)
{
    switch (e.Key)
    {
        case Key.Enter:
            vw.Method1();
            break;
        case Key.Tab:
            vw.Method2();
            break;
        default:
    }
}

Or use commands:

public static class Commands
{
    public static RoutedCommand Command1 = new RoutedCommand();
    public static RoutedCommand Command2 = new RoutedCommand();
}
 <TextBox>
     <TextBox.CommandBindings>
         <CommandBinding Command="{x:Static local:Commands.Command1}"
                         Executed="Command1_Executed" CanExecute="Command1_CanExecute"/>
         <CommandBinding Command="{x:Static local:Commands.Command2}"
                         Executed="Command2_Executed" CanExecute="Command2_CanExecute"/>
     </TextBox.CommandBindings>
     <TextBox.InputBindings>
         <KeyBinding Key="Enter" Command="{x:Static local:Commands.Command1}"/>
         <KeyBinding Key="Tab" Command="{x:Static local:Commands.Command2}"/>
     </TextBox.InputBindings>
 </TextBox>

If you have not used commands before make sure to read this overview.

Upvotes: 5

Related Questions