Bind TextBox on Enter-key press

Binding TextBox on Enter-key press: Easy solutions for XAML
Do you find it annoying when the databinding on a TextBox only happens when it loses focus? 😩 Well, I'm here to tell you that there is an easy way to make the databinding happen when you press the Enter key on the TextBox, right in your XAML code! 🚀
The common problem: Default TextBox databinding
By default, the databinding on a TextBox is TwoWay, but it only commits the text to the associated property when the TextBox loses focus. This can be frustrating, especially if you want to update the property immediately after pressing the Enter key. 😤
The XAML solution: Trigger-based databinding
Thankfully, there is a simple and elegant solution using XAML triggers. With triggers, you can specify actions to be performed when a specific event occurs, such as when the Enter key is pressed. Let's dive into the code! 💻
<TextBox>
<TextBox.Triggers>
<EventTrigger RoutedEvent="KeyUp">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Text">
<DiscreteObjectKeyFrame KeyTime="0">
<DiscreteObjectKeyFrame.Value>
{Binding Text, UpdateSourceTrigger=Explicit}
</DiscreteObjectKeyFrame.Value>
</DiscreteObjectKeyFrame>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
<EventTrigger.Conditions>
<Condition Property="Key" Value="Enter" />
</EventTrigger.Conditions>
</EventTrigger>
</TextBox.Triggers>
</TextBox>In this example, we create an EventTrigger for the KeyUp event on the TextBox. Within the EventTrigger, we define an action to be performed when the Enter key is pressed, using the BeginStoryboard element. Inside the Storyboard, we use the ObjectAnimationUsingKeyFrames to animate the Text property of the TextBox.
The magic happens when we set the UpdateSourceTrigger of the Text binding to Explicit. This tells the databinding to update the source (the associated property) only when explicitly triggered.
Using the solution in complex scenarios
But what if the TextBox is inside a complex DataTemplate? 🧩 Not to worry! This solution works perfectly fine even within DataTemplates. Simply apply the same code within the DataTemplate, and the databinding will happen when the Enter key is pressed, regardless of its location.
Take action now!
Now that you have an easy and elegant solution to bind your TextBox on Enter-key press, go ahead and give it a try! Let me know in the comments if you found this solution helpful, or if you have any other cool XAML tricks up your sleeve. Happy coding! 💪👩💻👨💻
Take Your Tech Career to the Next Level
Our application tracking tool helps you manage your job search effectively. Stay organized, track your progress, and land your dream tech job faster.


