Saturday, June 2, 2012

Stop Checking CanExecute!

I stumbled upon an interesting problem in WPF. I've only seen a few rumblings about it on the internet so it may just be me doing something stupid. I can reproduce it so that's enough for me to look into it.

It's a common setup. There's a view model that manages workspaces (tabs, windows, whatever) similar to Josh Smith's example. However, when removing a view model from the ObservableCollection my view continues to poll the CanExecute of the commands it's bound too. No big deal, just set them to null and raise property changed and problem solved. Well what happens if you just want to unbind your current view and rebind to a new view? The view model has all the state in MVVM after all.

You could have some sort of unbind implementation on your workspaces that will null your commands and reinitialize them (bleh). The simplest option I've found is to set DataContext to null on your view when it unloads.

You can then just inherit from this control and call it a day.

Here's a project demonstrating the problem.