Validate a Textbox on LostFocus RRS feed

  • Question

  • On the LostFocus event of textbox, I am checking that the number is greater than 10.  If it is not, I want to show a messagebox, and then put the focus back in the textbox.  The code below is making the lostfocus event continuously fire:

    private void txtBillAmount_LostFocus(object sender, RoutedEventArgs e)
                if (Convert.ToDecimal(txtBillAmount.Text) <= 10)
                    MessageBox.Show("Bill amount must be greater than ten.");

    Sunday, October 13, 2019 5:38 PM

All replies

  • in WPF, validation is done with ValidationRules:
    How to: Implement Binding Validation
    Sunday, October 13, 2019 6:45 PM
  • Thanks, I understand that, but I'd like to get a solution using the above code.  Doesn't make sense to me that lost focus is being called when I set focus to the textbox.
    Sunday, October 13, 2019 7:17 PM
  • the event is a RoutedEvent, bubbling up from the contained TextBoxBase.
    so I guess when you are handling LostFocus of the TextBoxBase and setting the focus to the parent TextBox control: this leaves the TextBoxBase again.
    This works:

    Dispatcher.BeginInvoke(new Action(() => tb.Focus()));

    As then the new Focus is only called after all then events of Leaving the TextBox are handled
    But I strongly recommend to use Validation.

    Btw: even with Windows Forms this was not allowed: Control.LostFocus Event


    Do not attempt to set focus from within the EnterGotFocusLeaveLostFocusValidating, or Validated event handlers. Doing so can cause your application or the operating system to stop responding. For more information, see the WM_KILLFOCUS topic.

    Sunday, October 13, 2019 9:04 PM