Click here to Skip to main content
11,804,008 members (76,466 online)
Click here to Skip to main content

WPF: MVVM (Model View View-Model) Simplified

, 20 May 2009 CPOL 277.9K 11.9K 177
Rate this:
Please Sign up or sign in to vote.
Provides a clear and simple sample that clearly illustrates MVVM and its usage


A few months ago, I took the leap from WinForms programming to WPF and quite naturally, I took to it like a duck to water. Well, to be honest I had been developing Silverlight applications since its inception and being that Silverlight is a subset of WPF, it required a low learning curve to catch on. However, the concept of Commanding was a bit different in WPF and I soon began to see how much more powerful Commanding in WPF was compared to Silverlight.

One of the areas in which Commanding is exemplary is in the way in which it complements MVVM. But what is MVVM, and why is it useful? This is the toughest concept (in my opinion) to grasp when it comes to WPF (and Silverlight) programming. Why you ask? Because it is simple and as developers we often like code or concepts that warp our minds, so when we figure it out we can brag to our peers how it only took 2 hours to understand and implement the next BIG thing (no I am not projecting). On a side note, I have found that everyone who blogs about MVVM complicates it by adding too much code which just throws you for a loop. Simplicity is the key to all things complicated. So let’s delve into a little theory and we will finish up with some short-to-the-point code.


The purpose of this post is to:

  1. Give a simple and clear definition of Model View View-Model
  2. Provide a clear and simple sample that clearly illustrates MVVM usage



Figure 1.

Just in case you cannot read the text in the image here it is below:

  1. The View holds a reference to the ViewModel. The View basically displays stuff by Binding to entities in the View Model.
  2. The ViewModel exposes Commands, Notifiable Properties, and Observable Collections to the View. The View Binds to these ViewModel entities/members
  3. The Model is your data and/or application objects that move data while applying Application Logic. If you have a Business Layer, then you might not need this.

Above is a simple figure that tells you exactly what MVVM is. In my own words, the ViewModel is the most significant in the entire pattern as it is the glue that sits between the View and the Model and binds both of them together. Now let’s explore some code.


The application you are about to see is very intricate in design and implementation and as such must not be criticized by anyone. Here is an overview of what the application does. It takes your first name, last name and age and displays it to you in a message box. Below is the really complicated class diagram.


Figure 2.

Let’s take a look at the PersonModel class which is the only Model in the application:

namespace OliverCode.MVVM.Model 
    internal class PersonModel : System.ComponentModel.INotifyPropertyChanged 
        private string firstName; 
        public string FirstName 
            get { return firstName; } 
                firstName = value; 
        private string lastName; 
        public string LastName 
            get { return lastName; } 
                lastName = value; 
        private int age; 
        public int Age 
            get { return age; } 
                age = value; 
#region INotifyPropertyChanged Members 
        public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; 
        private void OnPropertyChanged(string propertyName) 
            if (PropertyChanged != null) 
                    new System.ComponentModel.PropertyChangedEventArgs(propertyName)); 

Person class implements the INotifyPropertyChanged interface which enables a WPF element to be immediately notified if any of the properties changed on a Person object.

Moving on… Let’s look at the View which is cleverly named, PersonView (quite creative if I might add).

<UserControl x:Class="OliverCode.MVVM.View.PersonView" 
Height="Auto" Width="Auto" 
<StackPanel Orientation="Vertical" Margin="4"> 
<!--Here is where the view gets a reference to the ViewModel Declaratively--> 
<local:PersonViewModel /> 
<StackPanel Orientation="Vertical" DataContext="{Binding Path=Person, Mode=TwoWay}"
<StackPanel Orientation="Horizontal"> 
<Label Content="First Name:" Margin="0,0,4,0"/> 
<TextBox Width="250" Text="{Binding Path=FirstName}"/> 
<StackPanel Orientation="Horizontal" Margin="0,5,0,0"> 
<Label Content="Last Name:" Margin="0,0,4,0"/> 
<TextBox Width="250" Text="{Binding Path=LastName}"/> 
<StackPanel Orientation="Horizontal" Margin="0,5,0,0"> 
<Label Content="Age:" Margin="35,0,4,0"/> 
<TextBox Width="50" MaxLength="3" Text="{Binding Path=Age}"/> 
<!—The Command is bound to the Property in the PersonViewModel call SavePersonCommand--> 
<Button Content="Save" HorizontalAlignment="Right" Width="80"
   Command="{Binding Path=SavePersonCommand}"/> 

The key take away from the XAML above is the way the PersonViewModel is attached to the PersonView’s DataContext. (This is the typical means by which the View gets a reference to the ViewModel.) Also pay attention to the Button element whose Command is using the Binding class to attach the SavepersonCommand, which is a property on the ViewModel. Typically, binding to a command is more complicated than this, but because of the WPF MVVM Toolkit 1.0 (which is located here) from the Microsoft Team, developers can now easily Bind to commands. I have included the DelegateCommand class in the project so you don't need to download it directly. There is also a CommandReference class whose purpose is to resolve limitations in WPF when binding data from XAML. (This is not used in the program.)

WPF MVVM Toolkit 1.0 Tidbits

There are several classes in the toolkit but the one you should pay attention to is the DelegateCommand. This class makes it easy to write a function to handle a gesture or command. Gestures can be thought of as any interaction that can initiate a command. I use the DelegateCommand directly in my PersonViewModel like so:

private DelegateCommand savePersonCommand; 
public ICommand SavePersonCommand 
        if(savePersonCommand == null) 
            savePersonCommand = new DelegateCommand(new Action(SaveExecuted), 
                new Func<bool>(SaveCanExecute)); 
        return savePersonCommand; 
public bool SaveCanExecute() 
    return Person.Age > 0 && !string.IsNullOrEmpty(Person.FirstName) && 
public void SaveExecuted() 
    System.Windows.MessageBox.Show(string.Format("Saved: {0} {1} - ({2})",
        Person.FirstName, Person.LastName, Person.Age)); 

Here is the entire personViewModel class:

namespace OliverCode.MVVM.ViewModel 
    internal class PersonViewModel 
        public PersonModel Person { get; set; } 
        private DelegateCommand savePersonCommand; 
        public ICommand SavePersonCommand 
                if(savePersonCommand == null) 
                    savePersonCommand = new DelegateCommand(new Action(SaveExecuted),
                        new Func<bool>(SaveCanExecute)); 
                return savePersonCommand; 
        public PersonViewModel() 
            //This data will load as the default person from the model attached to
            //the view 
            Person = new PersonModel 
			{ FirstName = "John", LastName = "Doe", Age = 999 }; 
        public bool SaveCanExecute() 
            return Person.Age > 0 && !string.IsNullOrEmpty(Person.FirstName) && 
        public void SaveExecuted() 
            System.Windows.MessageBox.Show(string.Format("Saved: {0} {1} - ({2})", 
                Person.FirstName, Person.LastName, Person.Age)); 

Simple, isn't it? I hope I have helped someone by saving them hours trying to find a simple demonstration of MVVM in WPF. Don't forget to check out

Thank you and happy coding.


  • 20th May, 2009: Initial post


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Software Developer (Senior) 4CoreDev
United States United States
No Biography provided

You may also be interested in...

Comments and Discussions

GeneralMy vote of 2 Pin
Oleh Zheleznyak29-Nov-14 6:37
memberOleh Zheleznyak29-Nov-14 6:37 
GeneralMy vote of 1 Pin
ben-ba29-Jul-14 6:23
memberben-ba29-Jul-14 6:23 
QuestionWPF-MVVM File upload and save functionality Pin
gunjdoll25-Jun-14 5:23
membergunjdoll25-Jun-14 5:23 
GeneralMy vote of 4 Pin
snehalgb11-Apr-14 0:14
groupsnehalgb11-Apr-14 0:14 
QuestionI got a question about communication between ViewModel and View Pin
thewalk_shuai16-Sep-13 20:22
memberthewalk_shuai16-Sep-13 20:22 
GeneralMy vote of 1 Pin
Jussi Palo6-Jun-13 23:39
memberJussi Palo6-Jun-13 23:39 
Questionhow do I notify the Person property when i change the firstname etc properties? Pin
danielicy3-Jun-13 0:08
memberdanielicy3-Jun-13 0:08 
QuestionNice article, but this line.... Pin
Jerry H.13-Mar-13 3:34
memberJerry H.13-Mar-13 3:34 
GeneralMy vote of 5 Pin
Derek_Ewing7-Sep-12 0:21
memberDerek_Ewing7-Sep-12 0:21 
GeneralMy vote of 5 Pin
Farhan Ghumra24-Aug-12 2:44
memberFarhan Ghumra24-Aug-12 2:44 
QuestionAwesome Article Pin
Ehsan Hafeez16-Jul-12 0:45
memberEhsan Hafeez16-Jul-12 0:45 
GeneralMy vote of 5 Pin
akr.18989@gmail.com20-Jun-12 23:21
memberakr.18989@gmail.com20-Jun-12 23:21 
GeneralMy vote of 5 Pin
asakura896-Jun-12 4:01
memberasakura896-Jun-12 4:01 
AnswerTry this site: Pin
Member 471378529-May-12 3:33
memberMember 471378529-May-12 3:33 
GeneralMy Vote of 5 Pin
BITA Moin26-Apr-12 6:08
memberBITA Moin26-Apr-12 6:08 
GeneralMy vote of 1 Pin
Member 858314521-Feb-12 20:05
memberMember 858314521-Feb-12 20:05 
QuestionMy Vote Is 4 Pin
makc666-Feb-12 23:37
membermakc666-Feb-12 23:37 
AnswerRe: My Vote Is 4 Pin
DranDane13-Sep-12 5:13
memberDranDane13-Sep-12 5:13 
GeneralRe: My Vote Is 4 Pin
makc6613-Sep-12 21:49
membermakc6613-Sep-12 21:49 
QuestionVery Excellent! but can you explain following? Pin
Sunasara Imdadhusen31-Jan-12 2:23
memberSunasara Imdadhusen31-Jan-12 2:23 
GeneralMy vote of 3 Pin
URVISH SUTHAR from Ahmadabad Gujarat, India26-Jan-12 21:54
memberURVISH SUTHAR from Ahmadabad Gujarat, India26-Jan-12 21:54 
GeneralMy vote of 5 Pin
Salam633110-Jan-12 23:09
memberSalam633110-Jan-12 23:09 
GeneralMy vote of 5 Pin
golinvauxb16-Nov-11 10:22
membergolinvauxb16-Nov-11 10:22 
GeneralMy vote of 5 Pin
Nithin Sundar5-Sep-11 1:06
memberNithin Sundar5-Sep-11 1:06 
GeneralMy vote of 5 Pin
Member 474865616-Mar-11 11:40
memberMember 474865616-Mar-11 11:40 
GeneralMy vote of 1 Pin
Vivek Krishnamurthy12-Mar-11 8:13
memberVivek Krishnamurthy12-Mar-11 8:13 
GeneralRe: My vote of 1 Pin
Salam633110-Jan-12 23:13
memberSalam633110-Jan-12 23:13 
GeneralRe: My vote of 1 Pin
Vivek Krishnamurthy24-Feb-12 20:55
memberVivek Krishnamurthy24-Feb-12 20:55 
GeneralMy vote of 5 Pin
JustinYip22-Aug-10 23:35
memberJustinYip22-Aug-10 23:35 
GeneralMy vote of 1 Pin
Nikolaj Lynge Olsson27-May-10 20:18
memberNikolaj Lynge Olsson27-May-10 20:18 
GeneralRe: My vote of 1 Pin
robsammons31-Mar-11 2:56
memberrobsammons31-Mar-11 2:56 
QuestionRevision for Visual Studio 2010 .Net 4.0? Pin
Fresh Mexican Food Fan20-Apr-10 4:56
memberFresh Mexican Food Fan20-Apr-10 4:56 
GeneralMy vote of 1 Pin
Member 39667831-Mar-10 12:04
memberMember 39667831-Mar-10 12:04 
GeneralNever mind... Pin
Les Pinter25-Mar-10 5:52
memberLes Pinter25-Mar-10 5:52 
GeneralThis article help me a lot to understand MVVM Pin
Member 436133015-Feb-10 19:19
memberMember 436133015-Feb-10 19:19 
GeneralVery helpful Pin
Maurizio Reginelli3-Jan-10 9:48
memberMaurizio Reginelli3-Jan-10 9:48 
GeneralNice starter. Pin
Muaddubby1-Dec-09 10:58
memberMuaddubby1-Dec-09 10:58 
GeneralBy jove, I think I've got it! Pin
Kittiewan29-Nov-09 10:38
memberKittiewan29-Nov-09 10:38 
GeneralA good intro to MVVM, but a minor nitpick. Pin
Pete O'Hanlon27-Nov-09 1:44
mvpPete O'Hanlon27-Nov-09 1:44 
GeneralNice! Succinct! Pin
Keith Fletcher18-Oct-09 17:06
memberKeith Fletcher18-Oct-09 17:06 
GeneralWhen you never heard of MVVM then this article is great. Pin
jbe822422-Aug-09 8:08
memberjbe822422-Aug-09 8:08 
GeneralVery Good Pin
Member 456543330-Jul-09 8:24
memberMember 456543330-Jul-09 8:24 
GeneralThank you. Simple and to the Point Pin
emadm1-Jun-09 10:51
memberemadm1-Jun-09 10:51 
QuestionCan somebody explain? Pin
Yury Goltsman27-May-09 4:42
memberYury Goltsman27-May-09 4:42 
AnswerRe: Can somebody explain? Pin
rmgalante24-Oct-09 6:45
memberrmgalante24-Oct-09 6:45 
GeneralRe: Can somebody explain? Pin
Yury Goltsman24-Oct-09 7:01
memberYury Goltsman24-Oct-09 7:01 
QuestionBinding to the DataModel or to the ViewModel ? Pin
vladisld21-May-09 20:42
membervladisld21-May-09 20:42 
AnswerRe: Binding to the DataModel or to the ViewModel ? Pin
Alphakoda22-May-09 4:18
memberAlphakoda22-May-09 4:18 
GeneralRe: Binding to the DataModel or to the ViewModel ? Pin
Jacob Stanley26-May-09 16:49
memberJacob Stanley26-May-09 16:49 
GeneralRe: Binding to the DataModel or to the ViewModel ? Pin
Alphakoda26-May-09 18:12
memberAlphakoda26-May-09 18:12 
I am tempted to say you are wrong but since this has to do with architecture and there is usually no right way of doing one thing when the solutions are all subjective, I will refrain and approach it from the perspective that I intended this article to be used.

You said "Just because you access the Model through a property on the ViewModel, doesn't mean that it's encapsulated any better" If you understand the MvvM pattern, you know that it is a specific version of the Presentation Model where instead of having the View Notify the PresentationModel about changes to the Model, MvvM uses the built in Binding power and Notifications which means you can write an application and not have any code in your view, but you need to expose a Model that can notify the view of its changes.

MvvM was specifically designed for WPF due to it's Binding capabilities. In essence, MvvM associates a View to a View-Model which is why I said that the "View gets a reference to the View-Model". Which ever way you implement this pattern, you will have to give the view a reference to the View-Model for it to be MvvM because that is the way the pattern was intended to be used so that you utilize the Binding power of WPF. This can be done declaratively in XAML or in code. I chose to do it declaratively as it satisfies the intent of my article which is to provide a simplistic approach that anyone can grasp.

Now let's say that you have a Model like I do, you said, this could be "all business logic and services required by a ViewModel" and this is very much true, but if the goal of "MVVM was to make it so that the View doesn't have to communicate with or know about your Model or how it is implemented" as you put it, then how would you pass data between the View and the View-Model. The View in my observation is merely the visual Extension of the View-Model which would implicitly imply that the View needs to be able to access the View-Model making the View design time ignorant and runtime dependent on the View-Model. The Diagram clearly shows that the View should have a reference to the View-Model and that the View-Model exposes the Model to the View and should contain application logic (not business logic). Even the article you included clearly stated that the View-Model is meant to serve the View.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.151002.1 | Last Updated 20 May 2009
Article Copyright 2009 by Alphakoda
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid