Introduction to Model/View/ViewModel pattern for building WPF apps
Model/View/ViewModel is a variation of Model/View/Controller (MVC) that is tailored for modern UI development platforms where the View is the responsibility of a designer rather than a classic developer. The designer is generally a more graphical, artistic focused person, and does less classic coding than a traditional developer.. The design is almost always done in a declarative form like HTML or XAML, and very often using a WYSIWYG tool such as Dreamweaver, Flash or Sparkle. In short, the UI part of the application is being developed using different tools, languages and by a different person than is the business logic or data backend. Model/View/ViewModel is thus a refinement of MVC that evolves it from its Smalltalk origins where the entire application was built using one environment and language, into the very familiar modern environment of Web and now Avalon development.
Model/View/ViewModel also relies on one more thing: a general mechanism for data binding. More on that later.
The Model is defined as in MVC; it is the data or business logic, completely UI independent, that stores the state and does the processing of the problem domain. The Model is written in code or is represented by pure data encoded in relational tables or XML.
The View in Model/View/ViewModel consists of the visual elements, the buttons, windows, graphics and more complex controls of a GUI. It encodes the keyboard shortcuts and the controls themselves manage the interaction with the input devices that is the responsibility of Controller in MVC (what exactly happened to Controller in modern GUI development is a long digression...I tend to think it just faded into the background. It is still there, but we don't have to think about it as much as we did in 1979). The View is almost always defined declaratively, very often with a tool. By the nature of these tools and declarative languages some view state that MVC encodes in its View classes is not easy to represent. For example, the UI may have multiple modes of interaction such as "view mode" and "edit mode" that change the behavior of the controls or the look of the visuals, but these modes can't always be expressed in XAML (though triggers are a great start). We will solve this problem later.
At this point data binding comes into play. In simple examples, the View is data bound directly to the Model. Parts of the Model are simply displayed in the view by one-way data binding. Other parts of the model can be edited by directly binding controls two-way to the data. For example, a boolean in the Model can be data bound to a CheckBox, or a string field to a TextBox.
In practice however, only a small subset of application UI can be data bound directly to the Model, especially if the Model is a pre-existing class or data schema over which the application developer has no control. The Model is very likely to have a data types that cannot be mapped directly to controls. The UI may want to perform complex operations that must be implemented in code which doesn't make sense in our strict definition of the View but are too specific to be included in the Model (or didn't come with the pre-existing model). Finally we need a place to put view state such as selection or modes.
The ViewModel is responsible for these tasks. The term means "Model of a View", and can be thought of as abstraction of the view, but it also provides a specialization of the Model that the View can use for data-binding. In this latter role the ViewModel contains data-transformers that convert Model types into View types, and it contains Commands the View can use to interact with the Model.
I will develop these ideas, and describe in particular how to bind the View to Commands on the ViewModel in later posts. But the quickest way to clarify this pattern is to provide some examples:
The above picture shows three editing panels in the Sparkle UI. Each has been developed using the Model/View/ViewModel pattern. The simplest is the Library Panel at the top. The Model is a list of assemblies (each an instance of System.Reflection.Assembly), and associated with each list of assemblies is a list of controls. The View is one of our Panel chrome controls and a series of Styles and DataTemplates that expose the assembly list in a ComboBox and the list of controls in a ListBox. We data bind the caption of the ComboBox directly to the name of the Assembly and the items of the listbox take their text from the name of the Control. The ViewModel has as state the currently selected Assembly and exposes Commands for inserting a control into the scene. Selection is one of the most common components of a ViewModel. But since controls have selection, you may wonder why selection isn't left in the View instead. This is done because often many controls in the view need to coordinate based on a single selection. It is easier to bind to a single representation of selection in the ViewModel than coordinate all the different controls in the view. In the Library, the selected Assembly determines what is selected by the ComboBox and also what list data is displayed by the ListBox. Additionally, the designer could decide to switch to using a ListBox for the assemblies and a ComboBox for the control list without copying over selection coordination logic from his original view.
The Appearance panel has as its Model the selected shapes or controls in Sparkle's editing area. The View has a ListBox that displays the interesting properties on the selection (basically all the Pen and Brush properties), buttons that determine whether the Brush or Pen is solid, gradient etc. and a color spectrum for editing color components. The ViewModel includes what property is selected, what gradient stop is selected when editing a gradient, data converters for mapping colors to text values and to positions in the color spectrum, and commands for changing the Pens and Brushes being edited. In this case the Model was given to us by Avalon, the View could easily be changed to something radically different, and the ViewModel provides an abstract representation for the reusable parts of this UI.
The final example is our Project panel. Here the Model is an MSBuild Project...again a Model class that was pre-existing. The View is a tree control, scrolling area, and contains context menus. The ViewModel adapts MSBuild concepts that were designed without Avalon in mind (and work perfectly fine from the command line) so we can data bind to them, and again contains selection and commands.
Once you've grokked the Model/View/ViewModel pattern any UI problem is quickly stated in its terms. In fact, the entire Sparkle UI is defined using the pattern. The "selected shapes or controls in the editing area" that is the Model for the Appearance panel is itself a ViewModel concept from our Scene editor. The layout of Panels inside Sparkle has a Model consisting of a list of all registered panels, a View made up of a Grid with splitters that position the views, and a ViewModel that includes what panels are currently visible and what logical containers they are in (editing area, right, left, bottom trays).
More later...
Comments
Anonymous
October 11, 2005
What's that collapsable panel that you use as a container for your editing panels there? Is it included with WPF?Anonymous
October 11, 2005
The panel is custom. I don't know if WPF will contain something similar by the time we release.Anonymous
October 11, 2005
I really like this pattern, it seems very logical and extensible. I'm definately looking forward to the power of WPF...but sigh we won't have it generally available for sometime yet. I was wondering if you had ever tried to implement this same pattern using winforms databinding? I have attempted it, but ended up getting stuck when it came to representing hierchial data and needing to deep bind ie bind to something like Customer.Name.First.Anonymous
October 11, 2005
What is it with you Microsoft people? "The Controller has faded"? WHAT PLANET ARE YOU ON? If I ever imagined that you might understand object-oriented programming one of these years, that hope is gone.
Take a couple of months, study Apple's Cocoa framework, learn how they implemented bindings, and save your company and all of your developers man-years of wasted effort.
The key concepts you need to understand are MVC, Messaging, the Target-Action pattern, the Notification pattern, and the Delegation pattern. The key implementations you need to understand are Key-Value Coding, Key-Value Observing, and Keypaths.Anonymous
October 23, 2005
Some Guy: this is just a terminology mismatch. What John calls a ViewModel would be called a view-controller in Cocoa. Check out the Cocoa Design Patterns Guide p 34(http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaDesignPatterns/CocoaDesignPatterns.pdf):
"The controller layer frequently contains many lines of code. To make this quantity of code more manageable, it is sometimes useful to subdivide the controller layer further into “model-controllers” and “view-controllers”.
A model-controller is a controller that concerns itself mostly with the model layer. It “owns” the model; its primary responsibilities are to manage the model and communicate with any view-controller
objects. Action methods that apply to the model as a whole will typically be implemented in a model-controller. The document architecture provides a number of these methods for you; for example, NSDocument automatically handles action methods related to saving files.
A view-controller is a controller that concerns itself mostly with the viewlayer. It “owns” the interface (the views); its primary responsibilities are to manage the interface and communicate with the
model-controller. Action methods concerned with data displayed in a view will typically be
implemented in a view-controller."Anonymous
December 11, 2006
PingBack from http://www.orbifold.net/default/?p=550Anonymous
September 29, 2007
Dear Dr. WPF, I am about to begin leading a rather large WPF project. I’ve worked on plenty of development efforts involving Windows Forms projects and even a few Win32 projects, but this ...Anonymous
January 20, 2008
PingBack from http://blog.quantumbitdesigns.com/2008/01/20/wpf-application-design-and-architecture/Anonymous
January 23, 2008
I just saw a GREAT presentation by Josh Smith on using the Model View Controller (MVC) pattern to develop WPF applications. Josh did an awesome job of breaking down the different pieces of t ...Anonymous
March 12, 2008
PingBack from http://bordercrossingstatsblog.info/tales-from-the-smart-client-introduction-to-modelviewviewmodel/Anonymous
March 24, 2008
Robby has just fired this shot in The Great Templating War Debate of 2008. I don't often disagree with Robby on platform issues, but... I am now compelled to reply with an opposing viewp ...Anonymous
March 25, 2008
Oh look... I did it again! I promised to write ‘G’ is for Generator and then I come out with ‘I’ is for Item Container. I’m like a bad TV series that just k ...Anonymous
April 15, 2008
It’s been a while, but I’ve started work on a new pet project. Significantly, it’s my first foray into Windows Presentation Foundation.Anonymous
May 21, 2008
Like a lot of people, I’ve developed software professionally for a lot of different environments: PCAnonymous
May 22, 2008
Listen to the show here! John Gossman , Microsoft Architect for WPF and Silverlight, discusses his experiencesAnonymous
May 24, 2008
Several drops ago we introduced a ViewModel composition spike. The purpose of this spike was to introduceAnonymous
May 24, 2008
Several drops ago we introduced a ViewModel composition spike. The purpose of this spike was to introduceAnonymous
May 24, 2008
Several drops ago we introduced a ViewModel composition spike. The purpose of this spike was to introduceAnonymous
May 28, 2008
PingBack from http://www.wowgoldip.com/2008/05/29/using-viewmodels-and-datatemplates-to-compose-your-ui/Anonymous
May 31, 2008
PingBack from http://scaleurl.com/silverlight/?p=100Anonymous
June 03, 2008
PingBack from http://vbasedev.wordpress.com/2008/06/04/yari-yet-another-refeactoring-interation/Anonymous
June 06, 2008
First I'd like to say that I'm stoked about the work the Prism team has been doing.  I haveAnonymous
June 12, 2008
PingBack from http://jaydennews.myfreegigs.com/wpfmvvm.htmlAnonymous
June 28, 2008
Introduction to the Model/View/ViewModel Pattern for Building WPF Apps Model/View/ViewModel is a variation of Model/View/Controller (MVC) that is tailored for modern UI development platforms where the View is the responsibility of a designer rather thanAnonymous
June 30, 2008
PingBack from http://www.rorydriscoll.com/2008/06/30/nothing-to-report/Anonymous
July 22, 2008
PingBack from http://blog.quantumbitdesigns.com/2008/07/22/wpf-application-design-and-architecture/Anonymous
July 29, 2008
PingBack from http://www.nablasoft.com/alkampfer/index.php/2008/07/29/binding-combobox-to-enum-in-silverlight/Anonymous
August 06, 2008
Après avoir participé à quelques projets WPF depuis maintenant un peu plus d'un an, je suis dans uneAnonymous
August 11, 2008
Après avoir participé à quelques projets WPF depuis maintenant un peu plus d'un an, je suis dans uneAnonymous
August 12, 2008
PingBack from http://www.silverlight-travel.com/blog/2008/08/12/model-view-viewmodel-m-v-vm-pattern/Anonymous
September 01, 2008
PingBack from http://chrisdonnan.com/blog/2008/09/01/wpf-model-view-viewmodel-i-see-the-wisdom/Anonymous
October 12, 2008
PingBack from http://www.silverlight-travel.com/blog/2008/10/13/caliburn-alpha-fuer-wpf-und-silverlight/Anonymous
October 25, 2008
PingBack from http://www.davidezordan.net/blog/?p=491Anonymous
November 10, 2008
PingBack from http://blog.webjak.net/2008/11/11/fire-collection-updated-events-from-a-special-silverlight-itemscontrol/Anonymous
November 13, 2008
PingBack from http://www.beacosta.com/blog/?p=55Anonymous
November 18, 2008
PingBack from http://www.paulstovell.com/blog/presentation-qmsdnug-smart-client-patternsAnonymous
November 30, 2008
[WPF] Considerazioni su M-V-VMAnonymous
November 30, 2008
Xaml的出现使得Win下非常有效的MVC变得复杂了很多很多,而WPF的发布使得Web程序和Win程序的鸿沟渐渐填平,对于模式的思考也渐渐浮出来:是使用复杂化的MVC,还是微软提出的MVP,抑或其他的模式。Anonymous
December 10, 2008
PingBack from http://www.adventuresinsoftware.com/blog/?p=282Anonymous
December 15, 2008
One common question when applying DDD is how to interpret other architecture’s concepts of a “model”Anonymous
December 22, 2008
PingBack from http://www.japf.fr/?p=90Anonymous
December 27, 2008
PingBack from http://www.adventuresinsoftware.com/blog/?p=284Anonymous
January 01, 2009
PingBack from http://www.dieajax.com/2007/10/15/10-minute-tutorial-javafx-basic-2d-graphics-and-animation/Anonymous
January 02, 2009
PingBack from http://newinfo.sysu.edu.cn/Snowwaft/?p=352Anonymous
January 12, 2009
PingBack from http://blogdivx.com/?p=7Anonymous
January 12, 2009
PingBack from http://blogdivx.com/?p=6Anonymous
January 12, 2009
PingBack from http://blogdivx.com/?p=9Anonymous
January 12, 2009
PingBack from http://blogdivx.com/?p=8Anonymous
January 13, 2009
Jag talar ofta med kunder och partners som vill använda vedertagna designmönster för att separera ansvaretAnonymous
January 19, 2009
PingBack from http://www.silverlight-travel.com/blog/2009/01/20/an-introduction-to-mvvm-in-wpf-with-karl-shifflett/Anonymous
January 31, 2009
The ViewModel pattern (more formally called the Model-View-ViewModel pattern, but that’s way tooAnonymous
February 03, 2009
When we created Silverlight Charting (background reading here and here ), we tried to make things asAnonymous
February 05, 2009
PingBack from http://berndhengelein.de/2009/01/artikel-ber-m-v-vm-im-msdn-magazin/Anonymous
February 06, 2009
PingBack from http://blog.lulutech.com/PermaLink,guid,080e3a6e-4989-470c-a9a5-0337ffed2108.aspxAnonymous
February 06, 2009
PingBack from http://herdingcode.com/?p=148Anonymous
February 08, 2009
PingBack from http://blog.sharplab.net/computer/cprograming/wpf/1812/Anonymous
February 12, 2009
PingBack from http://wesaday.wordpress.com/2009/02/12/model-view-viewmodel-in-wpf-part-i/Anonymous
February 14, 2009
PingBack from http://berndhengelein.de/2009/02/tools-fr-wpf-und-silverlight-entwickler/Anonymous
February 15, 2009
In this article I will explain how to implement MVVM pattern in Silverlight. I was very overjoyed whenAnonymous
February 16, 2009
PingBack from http://blog.lulutech.com/PermaLink,guid,470ef8fd-6ad9-4a38-8724-229cfdc0d4ce.aspxAnonymous
February 19, 2009
PingBack from http://blog.sharplab.net/computer/cprograming/wpf/1840/Anonymous
February 26, 2009
Over the years I have spent a fair amount of time thinking about design patterns surrounding the presentationAnonymous
February 26, 2009
You may have noticed the new look for the Twilight Twitter Badge on my blog a few weeks ago. I wantedAnonymous
February 26, 2009
PingBack from http://www.silverlight-travel.com/blog/2009/02/27/twilight-15-multiple-views-with-mvvm/Anonymous
February 28, 2009
早在2005年,John Gossman写了一篇关于Model-View-ViewModel模式的博文,这种模式被他所在的微软的项目组用来创建ExprAnonymous
March 01, 2009
PingBack from http://steveluo.wordpress.com/2009/03/01/mvvm-how-to/Anonymous
March 02, 2009
PingBack from http://vincenthomedev.wordpress.com/2009/03/02/model-view-viewmodel-mvvm-screencast-for-silverlight-and-wpf/Anonymous
March 03, 2009
PingBack from http://virtualdreams.com.br/blog/2009/03/wpf-dicas-para-comear-com-mvvm/Anonymous
March 11, 2009
The comment has been removedAnonymous
March 14, 2009
The .NET Micro Framework SDK comes with a customizable emulator that allows extensions to the emulatedAnonymous
April 08, 2009
PingBack from http://marlongrech.wordpress.com/2009/04/08/mvvm-mediator-acb-cool-wpf-app-the-mvvm/Anonymous
April 10, 2009
Launching a custom dialog for editing on the DataGrid is another somewhat common request that I see fromAnonymous
April 27, 2009
Here are follow up resources for Paul Sheriff’s geekSpeak on WPF for the Business Developer . Be sureAnonymous
April 27, 2009
PingBack from http://microsoft-sharepoint.simplynetdev.com/resources-for-geekspeak-wpf-for-the-business-programmer-with-paul-sheriff/Anonymous
April 27, 2009
PingBack from http://www.codedstyle.com/resources-for-geekspeak-wpf-for-the-business-programmer-with-paul-sheriff-2/Anonymous
April 27, 2009
PingBack from http://www.codedstyle.com/resources-for-geekspeak-wpf-for-the-business-programmer-with-paul-sheriff/Anonymous
April 27, 2009
PingBack from http://asp-net-hosting.simplynetdev.com/resources-for-geekspeak-wpf-for-the-business-programmer-with-paul-sheriff/Anonymous
April 30, 2009
Thanks again to Marc Schweigert for hosting last night’s DevDinner in Reston. My blog is at www.irritatedVowel.com/BlogAnonymous
May 04, 2009
http://www.flickr.com/photos/richardmoross/3064808115/ No we’re not actually making a movie about ViewAnonymous
May 18, 2009
Recently Glenn Block asked some questions of the community concerning what support Microsoft should offerAnonymous
May 19, 2009
PingBack from http://hoachau.wordpress.com/2009/05/19/xaml-vs-c-composite-collection/Anonymous
May 19, 2009
PingBack from http://hoachau.wordpress.com/2009/05/20/xaml-vs-c-composite-collection-repost/Anonymous
May 31, 2009
PingBack from http://cocoaconvert.net/2009/05/31/two-way-data-binding-in-cocoa/Anonymous
June 04, 2009
WPF e il View model, qualche risorsa utile.