【问题标题】:Attached propedrties in WPF and event wiringWPF 中的附加属性和事件连接
【发布时间】:2011-01-25 11:01:26
【问题描述】:

我有一个附加属性(例如,它将文本框中的文本大写)。显然我必须订阅 TextBox 的 TextChanged 事件以在每次文本更新时将其大写。

public class Capitalize
{
    // this is for enabling/disabling capitalization
    public static readonly DependencyProperty EnabledProperty;
    private static void OnEnabledChanged(
        DependencyObject d, 
        DependencyPropertyChangedEventArgs e)
    {
        var tb = d as TextBox;
        if ((bool)e.NewValue)
        {
            tb.TextChanged += new TextChangedEventHandler(tb_TextChanged);
        }
        else
        {
            tb.TextChanged -= new TextChangedEventHandler(tb_TextChanged);
        }
    }
}

正如我们所见,我们将事件处理程序添加到 TextBox(如果我理解正确的话)创建一个强引用。这是否也意味着由于强大的 ref GC 无法收集 TextBox?如果是 - 我应该在什么时候取消连接事件以便可以收集 TextBox?

【问题讨论】:

  • 刚知道强引用是相反的(=> 从 TextBox 到 Capitalize),所以收集 TextBox 本身没有问题。

标签: wpf events garbage-collection attached-properties


【解决方案1】:

引用反过来,即文本框保存对事件处理程序的引用。所以没有内存泄漏的可能性。

【讨论】:

  • 感谢您的澄清。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-18
  • 1970-01-01
  • 1970-01-01
  • 2016-03-02
  • 2021-12-27
相关资源
最近更新 更多