I need to execute code before a wpf user control is unloaded and cancel the unloading if certain conditions are met and keep the control open in its current state in the ui…
Is there any way I can accomplish this? I couldnt see anything like unloading event?
Thanks,
Unloadedis 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
Parentproperty in yourInitializedevent handler.Then, when
Unloadedis called, make your tests in theUnloadedevent handler, and if your conditions are met, re-insert the control into the logical tree. TheContentControlclass has an explicitAddChildprotected method you could call.There are probably some side effects to watch out for; According to the documentation,
Unloadedis called when themes are changed at the OS level, when the WPF visual tree reconstitutes itself.