Reputation: 584
This is my xaml structure
<StackPanel>
<m:TextBoxWithEllipsis IsEllipsisEnabled="True"
Name="A"
LostFocus="text_LostFocus"/>
<m:TextBoxWithEllipsis IsEllipsisEnabled="True"
Name="B"
LostFocus="text_LostFocus"/>
</StackPanel>
=> This structure can loop more. Such as:
<StackPanel>
<m:TextBoxWithEllipsis IsEllipsisEnabled="True"
Name="A"
LostFocus="text_LostFocus"/>
<m:TextBoxWithEllipsis IsEllipsisEnabled="True"
Name="B"
LostFocus="text_LostFocus"/>
</StackPanel>
<StackPanel>
<m:TextBoxWithEllipsis IsEllipsisEnabled="True"
Name="A"
LostFocus="text_LostFocus"/>
<m:TextBoxWithEllipsis IsEllipsisEnabled="True"
Name="B"
LostFocus="text_LostFocus"/>
</StackPanel>
In .cs file, I define event lost focus as below
private void text_LostFocus(object sender, RoutedEventArgs e)
{
TextBox textbox = ((TextBox)sender);
if (textbox.Text.Trim().Length == 0)
{
System.Windows.Forms.DialogResult result1 = System.Windows.Forms.MessageBox.Show("Empty string!", "Warning",
System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Exclamation);
textbox.Dispatcher.BeginInvoke((Action)(() => { textbox.Focus(); }));
return;
}
textbox.ScrollToHome();
}
The problem: If there are >= 2 textbox having value is empty ("").
==> Program always show the message box => If I click OK button, It show another. It occur forever. I can't close the program.
Question: If I have >= 2 empty textbox and I do same as problem above. How can I change the function text_LostFocus
to solve the problem???
DEFAULT:
Value of these textbox is always empty (DEFAULT)
Must use BeginInvoke => Because I want when user click to texbox, user must enter least a character.
Upvotes: 2
Views: 38757
Reputation: 5666
I wouldn't use a MessageBox if I were you. WPF has a very good "binding validation framework" (take a look here for a very good tutorial). Otherwise I would create a "warning" label located close each textbox:
<StackPanel>
<m:TextBoxWithEllipsis IsEllipsisEnabled="True"
Name="A"
LostFocus="text_LostFocus"/>
<TextBlock Name="AWarning" Foreground="Red" />
<m:TextBoxWithEllipsis IsEllipsisEnabled="True"
Name="B"
LostFocus="text_LostFocus"/>
<TextBlock Name="BWarning" Foreground="Red" />
</StackPanel>
Then in the code-behind:
private void text_LostFocus(object sender, RoutedEventArgs e)
{
TextBox textBox = ((TextBox)sender);
TextBlock textBlock = FindName(String.Concat(textBox.Name, "Warning")) as TextBlock;
textBlock.Text = String.IsNullOrWhiteSpace(textBox.Text) ? "Empty string!" : String.Empty;
}
Upvotes: 7