开发者

Strategy for unsubscribing event handlers

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 Vie开发者_StackOverflow社区w 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?


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().


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜