views:

54

answers:

2

In my WPF application I have a View that is given a ViewModel, and when given this View it adds event handlers to the ViewModel's PropertyChanged event. When some action occur in the GUI I remove the View and add another View to the holding container - where this new one is bound to the same ViewModel.

After this has happened the old View still keeps handling PropertyChanged events in the ViewModel. I'm assuming this happens because the View hasn't been collected by the Garbage Collector yet, and therefore is alive? Well - I need it to stop. My assumption is that I need to manually detach the event handler from the ViewModel? Is there a best-practice on how to handle this?

+2  A: 

The strategy I'm using is to make the View implement IDisposable, and have the Dispose function of the View unsubscribe the event handlers. Then whoever is responsible for adding the view there needs to call Dispose() on the old View first.

Works like a charm, but is this a valid use of IDisposable?

stiank81
+2  A: 

Perhaps subscribing to the view's Unloaded event and detaching in the Unloaded event handler there is a little cleaner, it would also not require users to call Dispose().

Ed Gonzalez
Thanks! I'm liking this solution much better than the Dispose solution.
stiank81