In wpf, is there a way to execute code before the control is unloaded...? like maybe an unloading event? In wpf, is there a way to execute code before the control is unloaded...? like maybe an unloading event? wpf wpf

In wpf, is there a way to execute code before the control is unloaded...? like maybe an unloading event?


Unloaded is fired when the control is removed from the WPF visual tree. As far as I've been able to read there is no "Unloading" event as there is, I think, in Windows Forms. But, "Unloaded" doesn't mean that the control is destroyed, just that it's removed from the visual tree.

Keep a reference to the control in a separate place in your code, along with a little bit of metadata about its parent control. You can probably collect that metadata by storing a reference to the Parent property in your Initialized event handler.

Then, when Unloaded is called, make your tests in the Unloaded event handler, and if your conditions are met, re-insert the control into the logical tree. The ContentControl class has an explicit AddChild protected method you could call.

There are probably some side effects to watch out for; According to the documentation, Unloaded is called when themes are changed at the OS level, when the WPF visual tree reconstitutes itself.


There is an Unloaded event on System.Windows.Controls.Control, but I don't know an elegant way to stop unloading the control with it.


private void UserControl_Unloaded(object sender, RoutedEventArgs e){     if (ConditionsMet) { e.Handled = true; }}

If ConditionsMet the Unloaded event will be set to true henceforth keeping your control in the VisualTree - your control does not Unload