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?
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.
精彩评论