My Technobabble

Lately there is a lot of momentum and interesting conversation around Model-View-View-Model. There’s several good resources out there that discuss the basics of the pattern, who the actors are that are involved and what role the play. I’ll let those speak for themselves, including John Gossman’s great post here, Martin Fowler’s post on the more general PresentationModel pattern and more recently Josh Smith’s MSDN article, Rob Eisenberg’s new series, and Ward Bell’s posts which touch on some of the deeper complexities involved.

In many of these discussions (not including the posts I referred to) it seems like one aspect of ViewModel get’s lost, which is “Why use it in the first place?” This leads to a lot of debate around details of implementation including one item in particular which is whether or not code in the code-behind is an anti-pattern. Building off of the stage Phil set in his great LOD post, I’ll say ViewModel is not a code-counting exercise.

These are all GREAT points. 

Something else Glenn covers is Commands:

The last thing I want to touch on relates to invoking commands, and usage of command parameters through element binding, vs using bound properties on the ViewModel. The user selects an item in the Order list, and double clicks. Do we a) Use element binding and have clicking on the “Open Order” button invoke the OpenOrder command passing in the currently selected order as a parameter, or b) Set the orders list selected item to bind to a SelectedOrder ViewModel property and then have a parameterless OpenOrder command which uses the SelectedOrder order property on the VM itself.

I agree with his assessment that this stuff should use method B.

My reasoning is sort of the same.  Element Binding is nice, but it does make the Designer responsible for something that should be in a Unit Test and this I feel is a no-no.

Element binding is useful for scaling with a slider, but NOT for changing display based on Persisted Data; that relationship belongs in the ViewModel.

Views can have code as long as they exclusively touch Display Only elements, an example would be Style Changes, if you need to invoke some code to load a resource, then that should be in the ViewModel, but to invoke a change based on binding, like a trigger, that may be perfectly fine in the View.

While we are still in the beginnings of applying these patterns to Silverlight, I should point out that if we are forced to overcome a “bug” in rendering, keep that in the View, because the ViewModel just gets muddied up if you don’t; especially if you intend to share your ViewModel with WPF.  Most likely the same “bug” would not exist in both UIs.  Then when a refresh is done and the “bug” goes away in Silverlight, you only have to deal with a change in the Silverlight View.

Maintainability is the key here and the reason these patterns exist.  Keep your code where it belongs for maintainability and you a following the pattern correctly.