views:

118

answers:

1

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!

+2  A: 

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 ;-)

winSharp93
Got it, thanks much.
eskerber