什么功能破坏了递归

问题描述 投票:0回答:1
c#
1个回答
0
投票

如果你看看微软的实现

你会发现这个:

  public static readonly DependencyProperty TextProperty =
          DependencyProperty.Register(
                  "Text", // Property name
                  typeof(string), // Property type
                  typeof(TextBox), // Property owner
                  new FrameworkPropertyMetadata( // Property metadata
                          string.Empty, // default value
                          FrameworkPropertyMetadataOptions.BindsTwoWayByDefault | // Flags
                              FrameworkPropertyMetadataOptions.Journal,
                          new PropertyChangedCallback(OnTextPropertyChanged),    // property changed callback
                          new CoerceValueCallback(CoerceText),
                          true, // IsAnimationProhibited
                          UpdateSourceTrigger.LostFocus   // DefaultUpdateSourceTrigger
                          ));

UpdateSourceTrigger.LostFocus
表示绑定源将在 TextBox 失去焦点时更新,而不是在文本更改时立即更新。在这种情况下,这会破坏递归。

我不知道这种行为将在未来版本或替代实现中持续存在的有力保证。事实上,TextBox 文档暗示只要值发生变化就会触发更改事件。

为了确保您的事件处理程序不会在更复杂的场景中触发递归,或者如果未来的 WPF 版本有不同的行为,您可以像这样明确地处理这种情况:

private bool _isHandlingEvent = false;

private void HeaderFilterChangedEventHandler(object sender, EventArgs e)
{
    if (_isHandlingEvent) return;

    try
    {
        _isHandlingEvent = true;
        ImplementationFilter.Text += "1";
    }
    finally
    {
        _isHandlingEvent = false;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.