How or when to cleanup RelayCommand objects in WPF/MVVM?
I am using the standard Josh Smith implementation of RelayCommand to implement ICommands in my WPF/MVVM application. See: WPF Apps with the MVVM Design Pattern
A few of my CanExecute methods take a long time to run. Individually, they aren't bad (a fraction of a second each). But I have noticed that the more commands that I bind to my UI, the slower the application responds (delays exceeding 10 seconds - yuck).
I believe it is because the RelayCommand CanExecuteChanged is hooking onto the CommandManager.RequerySuggested event and my ViewModel template calls CommandManager.InvalidateRequerySuggested() as part of the IDataErrorInfo validation.
My ViewModels implement IDisposable, so I have tried to take advantage of the OnDispose method to clean up my RelayCommands, but the ICommand.CanExecute methods continue to be called even after my VM is disposed of.
That leads me to conclude that something (the CommandManager?, the View?) is holding a reference to the RelayCommand.
Does anyone have a good pattern for rel开发者_运维问答easing and disposing of RelayCommands to prevent them from being requeried after their desired lifetime has expired?
Is there a better way to manage when CanExecute should be called?
You can take out the CommandManager.RequerySuggested
and use MVVM Light's RelayCommand implementation. Note: this requires you to explicitly call RaiseCanExecuteChanged()
anytime you want CanExecute to be updated.
精彩评论