【发布时间】:2015-01-07 13:10:11
【问题描述】:
这是我的 xaml 结构
<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>
<StackPanel>
<m:TextBoxWithEllipsis IsEllipsisEnabled="True"
Name="A"
LostFocus="text_LostFocus"/>
<m:TextBoxWithEllipsis IsEllipsisEnabled="True"
Name="B"
LostFocus="text_LostFocus"/>
</StackPanel>
在 .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();
}
问题:如果有 >= 2 个文本框的值为空 ("")。
- 我单击第一个空文本框 => 我没有输入任何字符。
- 然后我点击第二个空文本框。
==> 程序总是显示消息框 => 如果我点击确定按钮,它会显示另一个。它永远发生。我无法关闭程序。
问题:如果我有 >= 2 个空文本框,并且我执行与上述问题相同的操作。怎么改函数text_LostFocus解决问题???
默认:
这些文本框的值始终为空(DEFAULT)
必须使用 BeginInvoke => 因为我希望当用户点击 texbox 时,用户必须输入至少一个字符。
【问题讨论】:
-
有趣的实现 XD 当你有两个文本框时,想想发生了什么: 1. 你输入了第一个 tb 2. 你没有输入任何东西然后你点击了第二个 3. tb1 的 lostfocus 事件触发并打开一个对话框,并再次关注 tb1 4. 因为 tb1 获得焦点,所以 tb2 的 lostfocus 事件触发并且它执行相同的操作,将焦点返回到 tb2 并继续进行无限循环。
-
另外 - 不需要
BeginInvoke。你已经在 UI 线程上。 -
我以为这是 WPF 而不是 WinForms,这个
System.Windows.Forms.DialogResult可以很容易地替换为System.Windows.MessageBox! -
我建议不要在有人离开文本框而未输入数据时显示弹出窗口:这真的很烦人。在视觉上标记它(例如,旁边有一个红十字);在满足最低要求之前也不要启用提交按钮。
-
@GSP
BeginInvoke不会像你说的那样做,它只是在特定的调度程序上运行代码。textbox.Dispatcher.BeginInvoke((Action)(() => { textbox.Focus(); }));应替换为textbox.Focus();