Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of WinForms TextBox.Validating event in WPF

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?

like image 484
Ryan Lundy Avatar asked Sep 11 '09 14:09

Ryan Lundy


3 Answers

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

like image 156
Martin Harris Avatar answered Sep 20 '22 21:09

Martin Harris


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));
    }
}
like image 34
Nicolas Avatar answered Sep 21 '22 21:09

Nicolas


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.

like image 44
MadanD Avatar answered Sep 23 '22 21:09

MadanD