Handling Load & Unload View Events

Topics: Prism v2 - WPF 3.5
Jun 15, 2009 at 11:29 AM

When a view is removed from region its and all its children's unload event gets called.  If/when the view insttance is loaded back into region the loaded event gets called for the view and its children. Because of this behavior any one time processing that needs to happen in loaded event now needs a special flag to make sure it doesn't get run more than once for the real lifetime of the view. But how do I handle unloading? I have an attached behavior that creates some event handlers on my view, and cleans up those event handlers when the attached element calls unload, but in Prism I can't do that since even after unload that same view instance could be shown again, but now necessary objects that have been cleaned up in unloaded are no longer available. What's a good decopuled way of knowing when an element/view is really destroyed and be able to react to it via an attached behavior?

Jun 17, 2009 at 6:47 PM

Hi Joe


If I understand your scenario correctly, you want to know whether a View is added/removed to a region. If you do not need them to be removed, but just deactivate it, Prism provides a way to do this. The IActiveAware interface allows you to monitor Activated/Deactivated events of a View related to a region. The following thread provides more details about this:

·         Using IActiveAware


Another possible approach, could be finding a way to persist the View’s state, so when you load it again you have access to the objects that were cleaned up.

You might also implement the IDisposable interface, and the controller whose responsibility is to manage the lifetime of that specific view, should call Dispose() on the view, so the view can now clean up the resources.


If I misunderstood your scenario and when you said “knowing when an element/view is really destroyed” you meant about to be GCd, you can always use its destructor.


Please let me know if this helps.


Damian Schenkelman