WPF 中的附加属性和事件接线
我有一个附加属性(例如,它将文本框内的文本大写)。显然,我必须订阅 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,这(如果我理解正确的话)创建了一个强引用。这是否也意味着由于该强引用,GC 无法收集 TextBox?如果是 - 我应该在什么时候取消事件连接以便可以收集 TextBox?
I have an attached property (e.g. its capitalizing the text inside a TextBox). Obvoiusly I must subscribe to the TextBox's TextChanged event to capitalize it every time text updates.
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);
}
}
}
As we see we add event handlers to the TextBox which (if I understand correctly) creates a strong reference. Does this also mean that because of that strong ref the GC cannot collect the TextBox? If yes - at which point should I unwire the event so that the TextBox can be collected?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
引用则相反,即文本框保存对事件处理程序的引用。所以不存在内存泄漏的可能性。
The reference goes the other way around, i.e. the text box holds the reference to the event handler. So there is no possibility for memory leaks.