Removing DataContextChanged / Loaded event handlers on XAML User Control

In an attempt to reduce memory leaks, I try to find out whether after this the event handler added the "DataContextChanged" or "Loaded" events in the user XAML control, that is (UserControl.xaml.cs):

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

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

+4
source share
1 answer

The short answer is no.

You only need to remove handlers when they hold the root object, which will prevent garbage collection. This will not happen if you create a child and one of its event handlers points to the parent because there are no dangling references to the child.

This will happen if you create a child, and the parent points to one of its event handlers in the child, because now the parent has a reference to the child that will support it in the root.

In the case mentioned above, it is completely internal - you add a link to your own class inside the class. When the user control is destroyed, it will not refer to links in the event handler of another class. Therefore, you do not need to remove the event handler.

+5
source

All Articles