9

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,

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
guest
  • 255
  • 4
  • 10
  • 1
    What is your use case for this? It sounds like you want something that works like Window.Closing which is a lot different than canceling a FrameworkElement.Unloaded event. There can be a lot happening around layout of parents and siblings when an element is being unloaded. – John Bowen Jul 13 '10 at 21:00
  • I have a similar problem, just in case you can help me http://stackoverflow.com/questions/5310724/wpf-unexpected-control-unload – Juan Mar 15 '11 at 14:40

3 Answers3

7

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.

Rob Perkins
  • 3,088
  • 1
  • 30
  • 51
0

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.

andyp
  • 6,229
  • 3
  • 38
  • 55
  • yea..i know about the unloaded event but depending on certain conditions I need to stop it from being unloaded... – guest Jul 13 '10 at 20:47
  • Does it have to be a UserControl? Or could you use a modal dialog which doesn't close if certain conditions aren't met? – andyp Jul 13 '10 at 20:53
-1
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

Chris
  • 5,882
  • 2
  • 32
  • 57