Disposing ViewModels & CanExecute Handlers
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).
精彩评论