views:

296

answers:

1

I have multiple xaml based pages stored as children of a canvas on another page. I add and remove the children pages as the application runs. However, pages that are removed from the children collection are still running and respond to keyboard shortcuts. How can I force the older pages to be removed completely?

+2  A: 

When you have your XAML pages displayed, are you registering for keyboard events? If so, are you forgetting to unregister from keyboard events when you remove those pages from the screen?

Since there is no "Unloading"-like event on either the UserControl or Page class in Silverlight (at least that I know of), what I do is have my pages implement a interface I define that contains a single method like "Cleanup" or "Close". Before I remove the control from the screen, I call Cleanup() on the control and have it do things like unregister from events it may have registered.

If you don't unregister from events the page's object will never be garbage collected because the CLR thinks the object is still live.

unforgiven3
Excellent. There were two events that weren't cleaned up properly. It appears to work very well now.
BenMaddox
Surely the disposable pattern is more appropriate than "Cleanup"?
Richard Szalay
I'm not sure how useful disposable pattern would be. Wouldn't I have to define a class for the pages? I attempted to do that before, but had trouble getting it to always work with xaml.
BenMaddox
Your pages are partial classes anyway - what Richard is saying is have your page class implement the standard IDisposable interface. You certainly could do it that way, but in my mind it's a question of semantics - are you "disposing" a page or "removing it from the screen"?
unforgiven3
In my mind, "disposing a page" is a far more heavyweight operation than a simple "close a page" or "cleanup a page" operation.
unforgiven3