I have been analyzing and estimating some Silverlight 4 and WPF projects recently, and will periodically get asked the question of what size of application is appropriate for utilizing the Model View ViewModel (MVVM) pattern. This is a great question, as adding any pattern will add a layer of complexity to a software project. If we are adding a pattern, we want to make sure that the benefits we get out of using a pattern outweigh the extra effort required to implement and maintain the pattern are worthwhile.
So, should you always use the MVVM pattern for Silverlight, WPF or other XAML applications? What if you have a very simple application, is it okay to just add your code to the codebehind page? In general, I am a big fan of keeping thing simple and understandable. However, I would argue that many Silverlight or WPF projects having anything beyond just a simple UI would benefit from using the MVVM pattern.
The MVVM pattern was designed specifically for the data binding capabilities that are available in XAML applications, allowing Views to be simple presentation that are abstracted from the business logic processing that should not happen at the user interface layer. The increased use of the MVVM pattern in the industry is another reason that MVVM should be seriously considered in any Silverlight or WPF application.
One of the primary benefits of the MVVM pattern is the unit testability of the codebase. Traditionally, software was developed with event handlers embedded right in the codebehind of the presentation. This tightly coupled approach of view to business logic can easily result in code that is difficult to maintain. With the MVVM pattern and unit testing in place, the codebase can remain robust over the lifetime of the software, and the intent of the developer can be well documented in the unit tests which are written (so long as unit tests are kept up to date).
Development Tool Integration
What’s more is that the MVVM concepts are being integrated into the Microsoft development tools. With Expression Blend 4, the UserControl with ViewModel Item is now available from the Add New Item menu option, as shown below.
This will create the plumbing for the View and ViewModel, automatically data bind the ViewModel to the View, and allow for Data Context binding right in the Expression Blend 4 editor.
Similarly, with a WPF application, you have the option to add a WPF Databound Application, which integrates the loose coupling of View and ViewModel in the project setup.
XAML application development is quickly becoming synonymous with the MVVM pattern. This is a robust pattern that will better organize your codebase for future maintainability and usability now and into the future. And it has never been easier to utilize this pattern in the Microsoft development tools.
This great demonstration gets into the details of how data binding can work in the Blend editor: