Should I use the Model-View-ViewModel (MVVM) pattern in Silverlight projects

design-patternsmvvmsilverlight

One challenge with Silverlight controls is that when properties are bound to code, they're no longer really editable in Blend. For example, if you've got a ListView that's populated from a data feed, there are no elements visible when you edit the control in Blend.

I've heard that the MVVM pattern, originated by the WPF development community, can also help with keeping Silverlight controls "blendable". I'm still wrapping my head around it, but here are some explanations:

One potential downside is that the pattern requires additional classes, although not necessarily more code (as shown by the second link above). Thoughts?

Best Answer

I definitely think you should use the MVVM pattern for Silverlight applications - and one of the benefits of the pattern is that you can actually make your application really blendable through some simple techniques. I often refer to "blendability" as "design for designability" - that you use certain techniques to make sure your application looks great in Blend.

One of the techniques - like Torbjørn points out - is to use a dependency injection framework and supply different implementations of your external services depending on wether the code is being executed in Blend or in the Browser. So I configure my container to use a dummy data provider when the code is executing in Blend, and that way you get design time support for your list boxes, data grids etc.

The challenge is often how to set the DataContext declaratively - so I often end up using a service locator class a a "front end" to the IoC container. That way I can bind the data context to a property on the service locator.

Another technique is create some kind of ObjectDataSource control (non visual) that has two properties: Design Time DataContext and RunTime Data Context. The control does the job of detecting where is being executing, and then setting the Parent DataContext to the right object.

Related Topic