WPF how to make textbox lose focus after hitting enter

17,078

You can also create a generic behavior which can be easily applied to any textbox within your application. Here is a sample behavior class:-

public class TextBoxEnterKeyUpdateBehavior : Behavior<TextBox>
{        
    protected override void OnAttached()
    {
        if (this.AssociatedObject != null)
        {
            base.OnAttached();
            this.AssociatedObject.KeyDown += AssociatedObject_KeyDown;
        }
    }

    protected override void OnDetaching()
    {
        if (this.AssociatedObject != null)
        {
            this.AssociatedObject.KeyDown -= AssociatedObject_KeyDown;
            base.OnDetaching();
        }
    }

    private void AssociatedObject_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
    {
        TextBox textBox = sender as TextBox;
        if (textBox != null)
        {
            if (e.Key == Key.Return)
            {
                if (e.Key == Key.Enter)
                {
                    textBox.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
                }
            }
        }
    }
}

To use this class in your xaml, just include it in textbox behaviors collection like this :-

<TextBox>
    <i:Interaction.Behaviors>
           <TextBoxEnterKeyUpdateBehavior />
    </i:Interaction.Behaviors>
</TextBox>

Here "i" refers to System.Windows.Interactivity namespace.

Share:
17,078
Dess
Author by

Dess

Updated on June 05, 2022

Comments

  • Dess
    Dess almost 2 years

    I created some textboxes and I want user to enter decimal values into them. In every application I have ever used, when I type something into the textbox and hit enter, the value is accepted and textbox lose focus. How can I do it in my app? I know it should be relatively easy to do it with a key event, but maybe there is a command or something. I searched the stackoverflow but I only found questions about how to keep focus after hitting enter...

  • cod3monk3y
    cod3monk3y almost 10 years
    Note that the proper import of the i namespace in XAML is xmlns:i="http://schemas.microsoft.com/expression/2010/intera‌​ctivity"
  • fhnaseer
    fhnaseer over 9 years
    Can I add this in the resource file? SO that I don't have to write it again and again,
  • j riv
    j riv almost 9 years
    To be honest, I'm suspicious with the huge amount of points such suggestions get just because they are more "XAML-y". The other answer is a single small function and a line for each key. This one needs a huge spam of <i:/> xaml for each box or at least an extra different solution to avoid that.
  • SQL Police
    SQL Police over 8 years
    Perfect, this is a great solution. One central piece of code. Exactly what I was looking for. Thank you.
  • mungflesh
    mungflesh about 8 years
    I found that the MoveFocus on sender did not work for me, but altering the line to MoveFocus on the e.OriginalSource as per the answer here did
  • NielW
    NielW over 7 years
    @jriv The other answer (textbox_KeyDown) is not even remotely MVVM. The only way that one would work is to couple your view to your view model, forever inseparable, and hard to test. Yes, it works great if you're not trying to do MVVM, but if you're using WPF, then why aren't you doing MVVM?
  • Rhys Bevilaqua
    Rhys Bevilaqua over 7 years
    @NeilW there is zero harm in baking UI logic into the UI. It's only the commands/text/state of the UI that MVVM models in the viewmodel to give you a layer that can be tested "like a user"
  • Massimiliano Kraus
    Massimiliano Kraus over 7 years
    @Precog I really can't understand what's the purpose of writing the double if if (e.Key == Key.Return) { if (e.Key == Key.Enter) ... why not if (e.Key == Key.Return || e.Key == Key.Enter) { ...? Further, since Key.Enter and Key.Return have the same int value... why don't you simply write if (e.Key == Key.Return) { ...
  • luka
    luka over 6 years
    The references System.Windows.Interactivity doesn't exist , so i can use it.
  • metal
    metal over 5 years
    If you don't want to change focus but just trigger the binding, change the MoveFocus call to something like: BindingOperations.GetBindingExpression( (DependencyObject)sender, TextBox.TextProperty )?.UpdateSource(); This allows you to not set the text box binding's UpdateSourceTrigger to PropertyChanged, which is sometimes undesirable.