TextChanged 事件 - 为什么这不会导致无限循环?

发布于 2024-09-03 06:29:41 字数 389 浏览 3 评论 0原文

在尝试做一些更复杂的事情时,我遇到了一种我不太理解的行为。

假设下面的代码处理 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

吃颗糖壮壮胆 2024-09-10 06:29:41

嗯 - 在更改/刚刚更改时设置 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;
    }
    //...
}

在引发 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):

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文