TextChanged 事件 - 为什么这不会导致无限循环?
在尝试做一些更复杂的事情时,我遇到了一种我不太理解的行为。
假设下面的代码处理 textChanged 事件。
private void textChanged(object sender, TextChangedEventArgs e)
{
TextBox current = sender as TextBox;
current.Text = current.Text + "+";
}
现在,在文本框中键入一个字符(例如 A)将导致事件触发两次(添加两个“+”),最终显示的文本仅为 A+。
我的两个问题是,为什么该事件只发生两次?为什么只有第一次运行事件才真正设置文本框的文本?
提前致谢!
While trying to do something a bit more complicated, I ran across a behavior I don't quite understand.
Assume the following code below handling the textChanged event.
private void textChanged(object sender, TextChangedEventArgs e)
{
TextBox current = sender as TextBox;
current.Text = current.Text + "+";
}
Now, typing a character in the textbox (say, A) will result in the event getting tripped twice (adding two '+'s) with the final text displayed being just A+.
My two questions are, why is the event hit just twice? And why does only the first run through the event actually set the text of the textbox?
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
嗯 - 在更改/刚刚更改时设置 Text 属性似乎由 TextBox 类显式捕获:
只需使用 Reflector 来查看 TextBox.OnTextPropertyChanged 内部>(缩短):
在引发 TextChanged 事件之前,字段 _isInsideTextContentChange 设置为 true。当再次更改 Text 属性时,TextChanged 事件不会再次引发。
因此:特点;-)
Well - setting the Text property while it is being changed / while it has just changed seems to be caught by the TextBox class explicitly:
Just use the Reflector to look inside TextBox.OnTextPropertyChanged (shortened):
The field _isInsideTextContentChange is set to true before the TextChanged event gets raised. When changing the Text property again, the TextChanged event thus is not raised again.
Therefore: Feature ;-)