Search code examples
c#wpftextboxcode-behindlostfocus

Wondering about TextBox methods


I have a TextBox for which I would like to run through a few conditions based on whether or not there is an integer entered in it. My operations take place from the code-behind of the window that the TextBox exists in.

Under the LostFocus event I would like to do the following:

  • Check if the string IsNullOrEmpty

    -If it is - set text to "Default Record"

  • Verify that the entered value is an Int

    If it isn't - Display a MessageBox(Ok Button), then set focus back on the TextBox

**This is what my LostFocus function looks like:

private void TextBox_LostFocus(object sender, RoutedEventArgs e) //Lost Focus
{
    if (string.IsNullOrEmpty(TextBox.Text))
        TextBox.Text = "Default Record";
    else if (Regex.IsMatch(TextBox.Text, @"^\d+$") == false)
    {
        MessageBox.Show("Illegal character in list.", "Warning!", MessageBoxButton.OK, MessageBoxImage.Warning);
        TextBox.Focus();
    }
}

The above function works well for testing whether or not the string IsNullOrEmpty, but I'm having problems with the else if condition. When I try to reset the focus back onto the TextBox I get an endless loop of MessageBoxes. Why is this and how do I fix it?

Update 1:

These are additional event handlers on the TextBox:

//State of View at startup
private void Document_Loaded(object sender, RoutedEventArgs e)
{
    //This is run because I need the TextBox to have focus at window startup
    TextBox.Focusable = true;
    TextBox.Focus();
}

xaml:

<UserControl Loaded="Document_Loaded" ... >

Solution

  • Do not attempt to set focus from within the Enter, GotFocus, Leave, LostFocus, Validating, or Validated event handlers. Doing so can cause your application or the operating system to stop responding...

    From MSDN