TextChanged Events - Why does this not result in an infinite loop?
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?
T开发者_StackOverflow社区hanks in advance!
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):
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;
}
//...
}
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 ;-)
精彩评论