Reputation: 3077
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?
Upvotes: 1
Views: 183
Reputation: 20756
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.
Upvotes: 1