C# – Can Silverlight 2.0 pages be removed from a collection manually (garbage collected)


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?

Best Solution

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.