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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With