Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF how to make textbox lose focus after hitting enter

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...

like image 744
Dess Avatar asked May 12 '14 15:05

Dess


1 Answers

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.

like image 69
Precog Avatar answered Sep 28 '22 07:09

Precog