Force WPF TextBox databinding when pressing enter

In a WPf application I am working on, I had the need for a TextBox to update its databinding not only when it lost focus, which is the default, but when the user pressed the enter key. I spent some time searching on the internet and so I thought I would put the solution here to hopefully save time for others. Unfortunately, this isn’t a pure XAML solution, but as far as I can tell, there isn’t one.

In the XAML create a TextBox with a KeyDown event handler

<TextBox Name="MyTextBox" Text="{Binding TextBinding}" KeyDown="OnTextBoxKeyDown"/>

Then in the code behind, force an update when the enter key is pressed.

private void OnTextBoxKeyDown(object sender, KeyEventArgs e)
{
   if(e.Key == Key.Enter)
   {
       MyTextBox.GetBindingExpression(TextBox.TextProperty).UpdateSource();
   }
}

Leave a Reply

Your email address will not be published. Required fields are marked *