【发布时间】: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