Cancel Unloaded event in a WPF application

.net, c#, wpf

Solution

Since Unloaded (and Loaded, for that matter) are not Tunneling events, I don't think there's any way to cancel this at the high level.

I'm curious as to what you are trying to achieve. Are you freeing resources associated with the child items? Are you concerned about the impact of returning to this page and re-initializing the resources? If so, perhaps an application cache is a better place to store them, so that you can tell when they were initialized, how often they were used, etc. This would also give you a centralized place to clean up cached resources in the case of memory pressure or a situation where you knew that resources from previous steps are invalid (e.g. you have finished a wizard, so you know you don't need any of the resources associated with earlier steps in the wizard).

Alternately, if you're looking for an opportunity to cancel the navigation entirely, I believe you're looking for the Navigating event. Canceling this event should halt the loading of the new resource and prevent the current page from changing.

--Adding information about a caching solution (wouldn't fit in a comment)

My first thought is that you should only optimize once you know something is actually a performance issue in the real world. If this does turn out to be a problem, you could create a singleton caching object that lives in your application to manage these objects. I'm sure there are some pre-built solutions that I am unaware of, but a Dictionary wrapped in an interface with string keys wrapped in a Singeton object would be sufficient for a simple application. You could then access it through a simple interface

CustomApplicationObjectCache[CACHE_KEY_CONSTANT_STRING] = new VisualBrush(...); //Or whatever type you have

Unless you are dealing with some very heavy-weight objects or object graphs, though, I suspect caching would be overkill and would probably get in the way of .NET doing the correct thing for garbage collection. I would recommend profiling your application and seeing if this is actually a performance problem for you.

Problem

I implemented a WPF application which use NavigationService to navigate between pages. When I switch from a page to another one, the Unloaded event is raised for each graphical element that belongs to the former page. Is there a way to cancel that event without having access to the graphical elements but only to the container?

Original source