WPF patterns : MVC, MVP or MVVM or…?

Introduction
Since XAML things have become a bit complicated in trying to conceptualize MVC architectures for Windows applications. The gap between web and win is narrowing and the whole WPF thing adds diverse possibilities to one’s toobox. What to use? Model-view-controler, the model-view-presenter or the new paradigm called model-view-viewmodel?
I have tried to understand what it’s all [...]

Introduction

Since XAML things have become a bit complicated in trying to conceptualize MVC architectures for Windows applications. The gap between web and win is narrowing and the whole WPF thing adds diverse possibilities to one’s toobox. What to use? Model-view-controler, the model-view-presenter or the new paradigm called model-view-viewmodel?

I have tried to understand what it’s all about and this is what I found out.

What’s the problem?

WPF has changed a few things:

  • through declarative programming (i.e. XAML) a lot of plumbing is created for you which especially in the context of databinding saves a lot of code. Another area is e.g. animations and styling; what previously had to be programmed in C# is now possible inside XAML through triggers or events.
  • in the MVC pattern the View is presenting the data from the Model but now XAML does this job and sometimes need things like value converters or the ObservableCollection to update the presentation
  • user controls in WPF allow you to define a default generic.xaml style which can be overriden when used inside an application, i.e. styling of existing controls is a new feature which adds flexibility to the presentation of the Model
  • XAML allows a wide variety of mechanisms to change things or to react to user actions; through the ICommand that is now defined in the framework, through triggers in XAML, through animations, through event bubbling or tunneling (which is also new)

The MVVM architecture

Overview

MVVM

DataModel

DataModel is responsible for exposing data in a way that is easily consumable by WPF. All of its public APIs must be called on the UI thread only. It must implement INotifyPropertyChanged and/or INotifyCollectionChanged as appropriate. When data is expensive to fetch, it abstracts away the expensive operations, never blocking the UI thread (that is evil!). It also keeps the data “live” and can be used to combine data from multiple sources. These sorts of classes are fairly straightforward to unit test.

ViewModel

A ViewModel is a model for a view in the application (duh!). It exposes data relevant to the view and exposes the behaviors for the views, usually with Commands. The model is fairly specific to a view in the application, but does not subclass from any WPF classes or make assumptions about the UI that will be bound to it. Since they are separate from the actual UI, these classes are also relatively straightforward to unit test.

View

A View is the actual UI behind a view in the application. The pattern we use is to set the DataContext of a view to its ViewModel. This makes it easy to get to the ViewModel through binding. It also matches the DataTemplate/Data pattern of WPF. Ideally, the view can be implemented purely as Xaml with no code behind. The attached property trick comes in very handy for this.

The lines between DataModels and ViewModels can be blurry. DataModels are often shown in the UI with some DataTemplate, which isn’t really so different than the way we use ViewModels. However, the distinction usually makes sense in practice. I also want to point out that there’s often composition at many layers. ViewModels may compose other ViewModels and DataModels. And, DataModels may be composed of other DataModels.

The ViewModel is a model of the view. That means: You want to DataBind a property from
your DataObject (model) to a property from your ViewObject (view) but you sometimes cannot bind directly to a CLR property of the model (because of converting or calculating). This is when ViewModel comes into play. It propagates the already calculated or converted value from your model, so you can bind this property directly to the view property.

The main thrust of the Model/View/ViewModel architecture seems to be that on top of the data (“the Model”), there’s another layer of non-visual components (“the ViewModel”) that map the concepts of the data more closely to the concepts of the view of the data (“the View”). It’s the ViewModel that the View binds to, not the Model directly.

The model

Using the INotifyPropertyChanged you can bubble changes up the stack. The reason that public methods should be on the UI thread is because the model could call long running or async stuff which would block the UI, though there are methods to let the UI thread handle property changes from a separate thread. See the doc on the Dispatcher object and the WPF threading model for more on this. Note in this context that you can let things happen in the background by means of the BeginInvoke() method of the Dispatcher and the paramter that specifies the priority. The SystemIdle in particular is interesting to be used when the Dispatcher is not busy.

The DataModel you can find in the download is mimiced from the Dan Crevier’s sample and can serve as an abstract base class for your own models.

Dispatcher things

The DispatcherTimer is reevaluated at the top of every Dispatcher loop.

Timers are not guaranteed to execute exactly when the time interval occurs, but are guaranteed to not execute before the time interval occurs. This is because DispatcherTimer operations are placed on the Dispatcher queue like other operations. When the DispatcherTimer operation executes is dependent on the other jobs in the queue and their priorities.

If a System.Timers.Timer is used in a WPF application, it is worth noting that the System.Timers.Timer runs on a different thread then the user interface (UI) thread. In order to access objects on the user interface (UI) thread, it is necessary to post the operation onto the Dispatcher of the user interface (UI) thread using Invoke or BeginInvoke. For an example of using a System.Timers.Timer, see the Disable Command Source Via System Timer sample. Reasons for using a DispatcherTimer opposed to a System.Timers.Timer are that the DispatcherTimer runs on the same thread as the Dispatcher and a DispatcherPriority can be set on the DispatcherTimer.

A DispatcherTimer will keep an object alive whenever the object’s methods are bound to the timer.

So, the right way to schedule things inside the WPF UI is something like;
[csharp]
private DispatcherTimer _timer;
timer = new DispatcherTimer(DispatcherPriority.Background);
timer.Interval = TimeSpan.FromMinutes(5);
timer.Tick += delegate { ScheduleUpdate(); };
timer.Start();

[/csharp]
the timer is injected implicitly in the thread associated to the dispatcher of the UI.

References

 

29 Responses to “WPF patterns : MVC, MVP or MVVM or…?”

  1. [...] example -ViewModel example -Advantages and disadvantages of M-V-VM -UML diagram of M-V-VM pattern -WPF Patterns -Dan Crevier’s DataModel-View-ViewModel Series -DataModel and [...]

  2. Majkez says:

    Hi,

    I wonder if there is any pattern for creating WPF smart client application in code-behind rather than in xaml? Declaring all UI components, databinding etc. in C#, with as less xaml as possible?

    Thanks!
    Majkez

  3. [...] un mal. Cela nous obligera ? utiliser encore les patterns MVP (Model View Presenter), MVVM (ModelView-ViewModel) . Mais hélas pour des petites applications tests, cela nous oblige ? ecrire plus de [...]

  4. [...] tabs and vertical text orientationSilverlight 2 beta 2, (breaking changes…) , Pierrick’s Blog on WPF patterns : MVC, MVP or MVVM or…?Ish Singh on Linq To Sql or Entity Framework?C on Don’t stop where they tell you toMe on [...]

  5. [...] example -ViewModel example -Advantages and disadvantages of M-V-VM -UML diagram of M-V-VM pattern -WPF Patterns -Dan Crevier’s DataModel-View-ViewModel Series -DataModel and [...]

  6. [...] we’ve had a rather large memory leak issue.  We’ve implemented our tiers in a pattern called MVVM. I wasn’t sure on how well this would work but to be honest, its been an amazing pattern to follow [...]

  7. WPF architecture comments…

    WPF architecture comments…

  8. [...] them all and you will get .Net 3.x – WPF/WCF/LINQ frameworks. With WPF patterns and all, in order to get most out of the framework theory part of OOD/OOP become even more [...]

  9. Other than the title and first paragraph I’m not seeing any mention of MVP at all here. It seems to me that MVP lies somewhere between MVC and MVVM without the assumption of magic data binding which I hope (haven’t tried it yet) works better than the data binding coming out of MS in the past.

  10. Have a look at this discussion and the MMVVVVM pattern.
    Seems to me people are looking for the ultimate, one-and-only, all-blessing and Microsoft-correct pattern. Personally, I think names and correctness don’t mean much if it does not suit your needs and the context in which you work. It all depends on your aims and I have no idea what kind of patterns I’m currently using in my (diagramming) applications. Pattern-based development is more a state of mind and a level of abstraction IMHO.

  11. [...] WPF patterns : MVC, MVP or MVVM or…? Since XAML things have become a bit complicated in trying to conceptualize MVC architectures for Windows applications. The gap between web and win is narrowing and the whole WPF thing adds diverse possibilities to one’s toobox. What to use? Model-view-controler, the model-view-presenter or the new paradigm called model-view-viewmodel? (tags: development design wpf mvvm) [...]

  12. The more things change, the more everything remains the same. I’m becoming more and more convinced that MVVM is really the same as MVP and not that different from MVC. What’s in a name? Anyhow, see this article where hot water is re-invented again.

  13. shiroica says:

    Hi, may I translate your interesting article to japanese and publicize on my blog? I’m looking for information about MVVM pattern, but I found no infomation written in japanese. I want to introduce this useful pattern in japanese.
    Thanks alot.

  14. Sure, go ahead. Just keep a reference to me, please.

  15. Looks cool Pierre, well done! Nice website presentation as well.

  16. tony says:

    First, I think the driving motivation for MVVM is that data binding is so central to the design of WPF. It is hard to build MVC/MVP when using data binding extensively.

    Second, I disagree with Francois. In MVP, the view does not know anything about the presenter or the model. In MVVM, the view binds directly to the model, which is a significant difference. Generally that should not be a problem because presumably the framework data binding is well tested.

  17. [...] MVC, MVP, and MVVM By billbelliveau Comparing MVC, MVP, and why MVVM Article: http://www.orbifold.net/default/?p=550 [...]

  18. aviade says:

    Hi tony, It’s incorrect to say that in ‘MVP’ the view does not know anything about the presenter or the model.

    About the relationship between the view and the presenter: MVP imposes no restriction on the kind of coupling between the view and the presenter, this is for the developers to decide. Personally, I prefer that the view will hold reference the presenter instance so it can directly invoke the appropriate method when user input arrives. DEREK GREER wrote fantastic article about the subject, please refer to:
    http://www.ctrl-shift-b.com/2008/11/model-view-presenter-styles.html

    About the relationship between the view and the model – there are two flavors of MVP, ‘Passive View’ and ‘Supervising Controller’, in ‘Passive View’ the view is passive and has no link to the model just like you said, however, in ‘Supervising Controller’ the view has link to the model. You can read all about it at:
    http://aviadezra.blogspot.com/2008/10/model-view-presenter-design-pattern.html

    Regards, Aviad

  19. Daniel Edstrom says:

    Great info, I’ll go with this design pattern 4 sure :-)

  20. Alexander says:

    Hi, good article but..
    You have described View, ViewModel and Model components of MVVM pattern. But what for is Controller needed on the picture? Can u describe?

  21. jbe says:

    Hi Alexander,

    What for is the Controller needed? You might have a look at this article: http://waf.codeplex.com/wikipage?title=Model-View-ViewModel%20Pattern&ProjectName=waf

Leave a Reply