[英]wpf LostFocus event of Textbox
This is my xaml structure 这是我的xaml结构
<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 在.cs文件中,我定义了事件丢失焦点,如下所示
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 (""). 问题 :如果> = 2,则文本框的值为空(“”)。
==> 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. 问题 : 如果我有> = 2个空文本框,我和上面的问题一样。 How can I change the function
text_LostFocus
to solve the problem??? 如何更改函数
text_LostFocus
来解决问题???
DEFAULT : 默认 :
Value of these textbox is always empty ( DEFAULT ) 这些文本框的值始终为空( DEFAULT )
Must use BeginInvoke => Because I want when user click to texbox, user must enter least a character. 必须使用BeginInvoke =>因为我想在用户点击texbox时,用户必须输入至少一个字符。
I wouldn't use a MessageBox if I were you. 如果我是你,我不会使用MessageBox。 WPF has a very good "binding validation framework" (take a look here for a very good tutorial).
WPF有一个非常好的“绑定验证框架”( 在这里看一个非常好的教程)。 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.