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
stringIsNullOrEmpty-If it is - set text to "Default Record"
Verify that the entered value is an
IntIf it isn't - Display a
MessageBox(Ok Button), then set focus back on theTextBox
**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" ... >