9

In WinForms I could handle the Validated event to do something after the user changed text in a TextBox. Unlike TextChanged, Validated didn't fire for every character change; it only fired when the user was done.

Is there anything in WPF I can use to get the same result, an event raised only after the user is done changing the text?

Ryan Lundy
  • 204,559
  • 37
  • 180
  • 211

4 Answers4

5

LostFocus will fire when the user moves from your textbox onto any other control.

Martin Harris
  • 28,277
  • 7
  • 90
  • 101
5

It seems that there is no native solution. The LostFocus event is a good idea. But when the user click on Enter, he wants the TextBox to validate the change. So here is my suggestion : use the LostFocus event and the KeyDown event when the key is Enter.

private void TextBox_LostFocus(object sender, RoutedEventArgs e)
{
    // code to lauch after validation
}

private void TextBox_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Enter)
    {
        // call the LostFocus event to validate the TextBox
        ((TextBox)sender).RaiseEvent(new RoutedEventArgs(TextBox.LostFocusEvent));
    }
}
Nicolas
  • 6,289
  • 4
  • 36
  • 51
  • Pay attention that a click on a button etc. is executed before the lost focus event. Use LostKeyboardFocus instead. – Felix Keil Jul 05 '18 at 09:11
2

LostFocus is not equivalent to Validate. It creates lots of problem when you have multiple text boxes on one screen and every text box has some logic written in Validate. In validate event you can control focus easily but not in LostFocus so easily.

MadanD
  • 107
  • 5
1

You can also try Binding.ValidationRules

Documented at : http://msdn.microsoft.com/en-us/library/system.windows.data.binding.validationrules.aspx

Here is the article to get started:

How to implement binding validations :

http://msdn.microsoft.com/en-us/library/ms753962.aspx

Signcodeindie
  • 776
  • 1
  • 10
  • 28