Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing DataContextChanged/Loaded Event Handlers on XAML User Control

In efforts to reduce memory leaks, I am attempting to figure out whether, after adding a handler to the "DataContextChanged" event or the "Loaded" event on a XAML User Control, i.e. (UserControl.xaml.cs):

    public MyUserControl()
    {
        InitializeComponent();
        DataContextChanged += new DependencyPropertyChangedEventHandler(MyUserControl_DataContextChanged);
        Loaded += new RoutedEventHandler(MyUserControl_Loaded);
    }

If I need to remove it. Does WPF handle this, or do I need to remove them manually?

like image 530
kodjeff1 Avatar asked Jul 22 '11 15:07

kodjeff1


1 Answers

Short answer -- no.

You only need to remove handlers when they would keep an object rooted, meaning prevent its garbage collection. This will not happen if you create a child object and have one of its event handlers point into a parent object, because there are no dangling references to the child object.

It will happen if you create a child object and the parent object points one of its event handlers into the child object, because now the parent object has a reference to the child object that will keep it alive (rooted).

In the case you specify above, it's totally internal -- you are adding a reference to your own class, inside the class. When the user control is destroyed, it won't have references sitting around in another class' event handler. So you do not need to remove the event handler.

like image 128
Ed Bayiates Avatar answered Nov 04 '22 02:11

Ed Bayiates