TextChanged events. Why doesn't this lead to an infinite loop?

When trying to do something more complex, I came across behavior that I do not quite understand.

Suppose the following code handles the textChanged event.

private void textChanged(object sender, TextChangedEventArgs e) { TextBox current = sender as TextBox; current.Text = current.Text + "+"; } 

Now, by typing a character in the text box (say, A), you will get a double response (adding two "+"), with the last text displayed as A +.

My two questions: why did this event happen only twice? And why only the first start of the event really sets the text of the text field?

Thanks in advance!

+7
wpf routed-events
source share
1 answer

Sets the Text property while it changes / while it has just changed, it seems to be explicitly 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 _isInsideTextContentChange field is set to true before the TextChanged event is raised. When the Text property is changed again, the TextChanged event is thus not raised again.

Therefore: Feature; -)

+7
source share

All Articles