为什么我的 LostFocus 事件出现无限循环
我是 C# 初学者,正在开发一个基本应用程序。
我想使用以下代码检查文本框的值是否为数字:
private void check_value(object sender)
{
TextBox tb = (TextBox)sender ;
if (!Utility.isNumeric(tb.Text)){
MessageBox.Show(tb.Text.Length.ToString());
tb.Focus();
}
}
private void Amount_1_LostFocus(object sender, RoutedEventArgs e)
{
check_value(sender);
}
当我在文本框中输入字母时,存在无限循环,并且似乎 tb.Focus() 实际上导致 LostFocus 事件被递归调用。 我不明白为什么调用对象的 Focus 方法会触发同一对象的 LostFocus 事件。
I'm a beginner with C# and I'm developing a basic application.
I want to check if the value of a textbox is a number with the following code :
private void check_value(object sender)
{
TextBox tb = (TextBox)sender ;
if (!Utility.isNumeric(tb.Text)){
MessageBox.Show(tb.Text.Length.ToString());
tb.Focus();
}
}
private void Amount_1_LostFocus(object sender, RoutedEventArgs e)
{
check_value(sender);
}
When I enter a letter in the textbox there is an infinite loop and it seems that the tb.Focus() actually cause the LostFocus event to be call recursively.
I don't understand why the call to the Focus method of an object triggers the LostFocus event of the same object.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
打开模态
MessageBox
会导致失去焦点。尝试挂钩Validating
事件。Opening the modal
MessageBox
is responsible for loosing the focus. Try hook toValidating
event.正如我之前在 Xaqron 提供的链接中所说,禁止在 LostFocus 事件中使用 Focus 方法。
当我开发 WPF 应用程序时,没有 Validating 事件和 CausesValidation 属性,因此验证内容的其他方法是使用 TextChanged 事件或使用绑定验证。
谢谢您的回答。
As i said before in the link provided by Xaqron it's said that it's forbidden to use the Focus method in the LostFocus event.
And as I'm developing a WPF application there is no Validating event and CausesValidation property, so the others ways to validate the content is to use the TextChanged event or use binding validation.
Thank you for your answers.
当然,在一个完全有效的程序中,您不应该在 LostFocus 事件中更改 Focus。这也适用于 Enter、GotFocus、Leave、Validating 和 Validated 事件,Ms 在文档 https://learn.microsoft.com/pl-pl/dotnet/api/system.windows.forms.control.lostfocus。
但是,在非常不寻常的情况下,您可以使用计时器来触发焦点的更改,从而绕过此问题。
Of course, in a perfectly valid program, you should not change Focus in the LostFocus event. This also applies to the Enter, GotFocus, Leave, Validating and Validated events, which Ms makes clear in the documentation https://learn.microsoft.com/pl-pl/dotnet/api/system.windows.forms.control.lostfocus.
However, in very unusual cases, you can use the timer to trigger changes to the Focus, bypassing this problem.