Search code examples
wpfeventsgarbage-collectionattached-properties

Attached propedrties in WPF and event wiring


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?


Solution

  • 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.