开发者

Disposing ViewModels & CanExecute Handlers

开发者 https://www.devze.com 2023-02-03 04:32 出处:网络
I recently had an exception because the CanExecute() of a command was called开发者_开发问答 after the screen was closed.

I recently had an exception because the CanExecute() of a command was called开发者_开发问答 after the screen was closed.

It's easily fixed by adding an extra check to the method but now I'm concerned about the lifetime performance of my application if the viewmodels aren't being disposed of properly.

I hook up commands by storing them as a property in the ViewModel, then bind to them in xaml.

so does anyone know why a closed window would continue to make calls to CanExecute() methods?


The reason why this is happening is that CommandManager has no clue that it should stop firing CanExecute until the handler gets garbage collected.

I had the same issue and I've solved it by setting DataContext of the window to null just after closing the window. It works fine assuming that the commands are bound to ViewModel (removing he DataContext unregisters the canExecute event handlers).


You probably still have command handlers or property changed handlers alive in your view model. Therefore, the view model still exists, and therefore the canexecute is still being executed. You probably subscribed to the CommandManager.RequerySuggested to update your commands. This event is invoked on ALL updates, not only on the window your view model is created for.

What you should (or can) do is subscribe to the Closed (window) or Unloaded (usercontrol) events to set the IsClosed state of the view model to false, and then remove the commands or disable them (you will have to implement this feature in the RelayCommand).

0

精彩评论

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