Eri*_*ber 7 .net wpf routed-events
在尝试做一些更复杂的事情时,我遇到了一个我不太了解的行为.
假设下面的代码处理textChanged事件.
private void textChanged(object sender, TextChangedEventArgs e)
{
TextBox current = sender as TextBox;
current.Text = current.Text + "+";
}
Run Code Online (Sandbox Code Playgroud)
现在,在文本框中键入一个字符(例如,A)将导致事件被触发两次(添加两个'+'),最终显示的文本只是A +.
我的两个问题是,为什么事件只发生了两次?为什么只有第一次通过事件才能实际设置文本框的文本?
提前致谢!
好吧 - 设置Text属性在它被更改/刚刚更改时似乎明确地被TextBox类捕获:
只需使用Reflector查看TextBox.OnTextPropertyChanged(缩短):
TextBox box = (TextBox) d;
if (!box._isInsideTextContentChange)
{
string newValue = (string) e.NewValue;
//...
box._isInsideTextContentChange = true;
try
{
using (box.TextSelectionInternal.DeclareChangeBlock())
{
//...
} //Probably raises TextChanged here
}
finally
{
box._isInsideTextContentChange = false;
}
//...
}
Run Code Online (Sandbox Code Playgroud)
在引发TextChanged事件之前,字段_isInsideTextContentChange设置为true .再次更改Text属性时,不会再次引发TextChanged事件.
因此:特征;-)
| 归档时间: |
|
| 查看次数: |
1174 次 |
| 最近记录: |