Understanding the Model View View Model for XAML with C#
The Model View View Model (MVVM) architectural pattern is used for the separation of concerns in applications. It’s popular in Microsoft’s XAML-based UI frameworks such as WPF, Silverlight or WinRT/XAML.
The MVVM architecture consists of the View layer (the UI design implementation), the View Model layer that provides bindable properties and commands to the view, and the Model layer that contains the application’s actual domain model and business logic. The connection between these layers is such that the View Model knows nothing about the View (it does not reference it) and the Model knows nothing about either of the other two layers.
The qualities of an application architected with the MVVM pattern are as follows:
- Maintainability – The separation of concerns and loose coupling helps modify one layer without affecting the other layers.
- Testability – Being able to replace the View as well as the View Model with a test fixture allows you to test the layers separately and avoid having to use unreliable and hard-to-maintain UI automation for all tests. That also helps overall maintainability of the code, since a change can be made in one part of the code, while tests reduce the risk of regressions in other areas.
- Blendability – View models can be easily replaced with design-time data and logic, so designers can create the views using Blend, independently of other development work.
- Ability to split work among multiple developers – Not only can the Views be implemented by designers or integrators, but also View models can be created separately from the Models by mocking up the Models.
- Portability – The View Models and Models can theoretically be reused in versions of the same app for different platforms.
MVVM was made possible in WPF – the original XAML framework – thanks to the XAML layer that is the declarative description of the View as well as bindings. MVVM allows you to declaratively specify which properties of the View Model are displayed or manipulated by the View, and you can specify the commands that allow you to represent actions executed by the View Model in the form of bindable properties. Anyone trying MVVM for the first time; however, soon notices problems with MVVM, such as:
- What are commands and why should I use them?
- What gets created first – The View or the View Model and how can you connect the two?
- Animations – How do you trigger an animation from the View Model or do something when an animation completes?
- Navigation and dialogs – Where can you initiate navigation and dialogs – from the Views or the View Models?
- State persistence – While saving the state of the application was a nice feature in the past, it is virtually required on modern platforms such as Windows Phone or Windows 8, so how do you store and restore the state of the View and the View Model?
- Non-bindable properties – A lot of the properties in the UI frameworks are not bindable, such as grid columns, row definitions, Windows Phone application bars or the style setter values.
- Bindable properties are rather verbose – Instead of using auto properties, even for the most basic bindable properties, you need to invoke property change notification events.
The languages and the UI frameworks lack built-in solutions to these problems, so the developer community has responded with many frameworks that try to address these issues. Some of the more well-known libraries maintained by known experts in the XAML community are listed at the end of this article.
MVVM Light, Caliburn.Micro, and Prism have grown to be the three most popular frameworks with the biggest communities around them with the best choices to start with, though the other libraries have interesting features that are worth checking too.
MVVM for WinRT
Should you use the BindableBase class and is it enough to build MVVM-based applications?
I still recommend using MVVM Light Toolkit or Caliburn.Micro for larger projects, since they provide features that you will most likely need sooner or later as your application grows, especially if you want to keep it implemented in clean MVVM fashion. As these libraries have grown in popularity, though, they have also grown in features and their built-in cross-platform support makes them more complicated and harder to study. Sure, with NuGet you can now have the latest version of MVVM Light referenced by your project within a few clicks, but then you cannot see the source code and it is harder to figure out how it works or how to use it, especially with the growing number of APIs available.
For smaller projects the BindableBase from the Visual Studio templates might just be enough for you. A snippet for observable properties as the “pp” snippet in my snippets helps a lot (just install the snippets and type pp[TAB] to insert an observable property in your view model). And do you really need commands to implement the MVVM pattern? A regular public method on the View Model works just as well, and if you need to disable or enable a button based upon whether a method can be executed, a regular observable property like CanExecuteMyMethod works just as well as a CanExecute method of a command. By the way, if you really want to, you can still create any MyCommand class that implements an ICommand interface – it is not much more code than using a DelegateCommand/RelayCommand of Prism/MVVM Light, though admittedly these do make it a lot easier to inline its implementation.
Not using a third party MVVM helper library has many benefits: no need to install anything, no dependencies, no reliance on reflection, no dead code in the form of unused framework APIs, and no need to justify using open source code at companies that do not generally allow it. It is what you get with the standard templates.
Of course these existing libraries have custom solutions to some specific problems and provide generic solutions to others, but eventually you stumble upon something that the library you chose just does not solve. In such cases I sometimes build my own reusable libraries or controls or just write some one-off piece of code that glues MVVM together. If the problem you need solved involves some custom interaction logic – you are going to be better off implementing a custom control or attached behavior than trying to stuff everything in the View Model.
Community XAML Frameworks
Here is a list of known experts in the XAML community and their maintained libraries:
- MVVM Light Toolkit (by Laurent Bugnion) – Most popular possibly because it really is pretty lightweight with just the basics of MVVM covered and the source code is easy to understand. For all platforms.
- Caliburn.Micro (by Rob Eisenberg) – A bit more complicated, but supports convention-based approach where bindings are not explicitly specified. For all platforms.
- Prism (by Microsoft patterns & practices team) – official guidance from Microsoft for developing composite applications with WPF, Silverlight and Windows Phone.
- WPF Application Framework (WAF) – a popular, WPF specific library
- ReactiveUI (by Paul Betts) – Based on Reactive Extensions – a bit exotic part of the .NET framework that is well suited for highly asynchronous applications. For all platforms.
- Cinch (by Sacha Barber) – A “Rich Full Featured WPF/SL MVVM Framework”.
- nRoute (by Rishi Oberoi) – A big library with a lot of features, available for all XAML platforms.
- Catel (by Geert van Horrik) – Another rich framework with MVVM support with support for all platforms.
- MVVM Foundation (by Josh Smith) – One of the early MVVM frameworks for WPF by an early MVVM advocate. Worth checking due to its small size and simple project structure.
- Jounce (by Jeremy Likness) – “Silverlight MVVM + MEF Framework”.
- Calcium (by Daniel Vaughan) – Composite application toolset for WPF/Windows Phone.
Ultimately using “code behind” (C#/VB/C++ code that accompanies the declarative XAML UI definition) does not invalidate MVVM. Experts in the field such as Laurent Bugnion have long been saying that MVVM is just a pattern and you should not be afraid of using code behind in your applications. However religiously it seems to be treated by many developers, if you just start by using View Models to drive your views – it is enough to reap most of the benefits of the pattern and will help you create a maintainable application. Unless you are building a big line of business applications, planning on unit testing your complicated view model logic, or doing a lot of UI development using Blend, you might not need a fully separated View and View Model.
If you are working on a big project though, or your project just grows big, you might consider one of the popular frameworks or building your own. At some point you will just find that you can’t live without a pub-sub implementation like MVVM Light’s Messenger or Prism’s EventAggregator. You will want to write unit tests and find a need for an IoC container, so you can mock and shuffle your components. Or you will want to bind everything even if Microsoft does not support the binding you want. Until then, though, feel free to start small and lean and worry about features rather than patterns. MVVM is just one of the tools to build an app and you might find that learning about custom layout logic, touch interaction, custom controls or behaviors is going to benefit you more than wondering which MVVM framework to use.
Safari Books Online has the content you need
Below are some Windows 8 books to get you started, or you can check out all of the Windows 8 books and training videos available from Safari Books Online. You can browse the content in preview mode or you can gain access to more information with a free trial or subscription to Safari Books Online.
|Building Windows 8 Applications with C# and XAML shows you how to build immersive, responsive touch apps for Windows 8 tablets, computers, and other devices! Top Microsoft MVP and Wintellect consultant Jeremy Likness shows how to leverage your existing C#, XAML, WPF, or Silverlight skills with new Visual Studio 12 tools and best practices to build incredibly powerful Windows 8/WinRT apps!|
|Get a head start on building apps for Windows 8. With a series of examples, Getting Started with Windows 8 Apps takes you through the process of creating complete touch-enabled apps that respond to native sensors. Through the course of the book, you’ll learn how to work with the Windows Runtime application model while building a Bing Image Search app.|
About the Author
|Filip Skakun is a Sr. Interactive Developer at Vectorform, where he creates user experiences for the world’s top brands, using the new and upcoming technologies. He is also the creator of the WinRT XAML Toolkit, a popular library for Windows 8 XAML developers and has a blog where he writes about programming. You can catch him on twitter.|