A Simple MVVM Example

In my opinion, if you are using WPF or Silverlight you should be using the MVVM design pattern. It is perfectly suited to the technology and allows you to keep your code clean and easy to maintain.

The problem is, there are a lot of online resources for MVVM, each with their own way of implementing the design pattern and it can be overwhelming. I would like to present MVVM in the simplest way possible using just the basics.

So lets start at the beginning.

MVVM

MVVM is short for Model-View-ViewModel.

Models are simple class objects that hold data. They should only contain properties and property validation. They are not responsible for getting data, saving data, click events, complex calculations, business rules, or any of that stuff.

Views are the UI used to display data. In most cases, they can be DataTemplates which is simply a template that tells the application how to display a class. It is OK to put code behind your view IF that code is related to the View only, such as setting focus or running animations.

ViewModels are where the magic happens. This is where the majority of your code-behind goes: data access, click events, complex calculations, business rules validation, etc. They are typically built to reflect a View. For example, if a View contains a ListBox of objects, a Selected object, and a Save button, the ViewModel will have an ObservableCollection ObectList, Model SelectedObject, and ICommand SaveCommand.

MVVM Example

I’ve put together a small sample showing these 3 layers and how they relate to each other. You’ll notice that other than property/method names, none of the objects need to know anything about the others. Once the interfaces have been designed, each layer can be built completely independent of the others.

Sample Model

For this example I’ve used a Product Model. You’ll notice that the only thing this class contains is properties and change notification code.

Usually I would also implement IDataErrorInfo here for property validation, however I have left this out for now.

The class inherits from ObservableObject, which is a custom class I use to avoid having to rewrite the property change notification code repeatedly. I would actually recommend looking into Microsoft PRISM’s NotificationObject or MVVM Light’s ViewModelBase which does the same thing once you are comfortable with MVVM, but for now I wanted to keep 3rd party libraries out of this and to show the code.

In addition to the INotifyPropertyChanged methods, there is also a debug method to validate the PropertyName. This is because the PropertyChange notification gets passed in as a String, and I have caught myself forgetting to change this string when I change the name of a Property.

Note: The PropertyChanged notification exists to alert the View that a value has changed so it knows to update. I have seen suggestions to drop it from the Model and to expose the Model’s properties to the View from the ViewModel instead of the Model, however I find in most cases this complicates things and requires extra coding. Exposing the Model to the View via the ViewModel is much simpler, although either method is valid.

Sample ViewModel

I am doing the ViewModel next because I need it before I can create the View. This should contain everything the User would need to interact with the page. Right now it contains 4 properties: a ProductModel, a GetProduct command, a SaveProduct command, an a ProductId used for looking up a product.

There is another new class here: the RelayCommand. This is essential for MVVM to work. It is a command that is meant to be executed by other classes to run code in this class by invoking delegates. Once again, I’d recommend checking out the MVVM Light Toolkit’s version of this command when you are more comfortable with MVVM, but I wanted to keep this simple so have included this code here.

Sample View

And now the Views. These are DataTemplates which define how a class should be displayed to the User. There are many ways to add these templates to your application, but the simplest way is to just add them to the startup window’s Resources.

The View defines two DataTemplates: one for the ProductModel, and one for the ProductViewModel. You’ll need to add a namespace reference to the Window definition pointing to your Views/ViewModels so you can define the DataTypes. Each DataTemplate only binds to properties belonging to the class it is made for.

In the ViewModel template, there is a ContentControl that is bound to ProductViewModel.CurrentProduct. When this control tries to display the CurrentProduct, it will use the ProductModel DataTemplate.

Notes

There are many other ways to do the things shown here, but I wanted to give you a good starting point before you start diving into the confusing world of MVVM.

The important thing to remember about using MVVM is your Forms, Pages, Buttons, TextBoxes, etc (the Views) are NOT your application. Your ViewModels are. The Views are merely a user-friendly way to interact with your ViewModels.

So if you want to change pages, you should not be changing pages in the View, but instead you should be setting something like the AppViewModel.CurrentPage = YourPageViewModel. If you want to run a Save method, you don’t put that behind a button’s Click event, but rather bind the Button.Command to a ViewModel’s ICommand property.

I started with Josh Smith’s article on MVVM, which was a good read but for a beginner like me, some of these concepts flew right over my head.

I’ve never done a blog or tutorial before, but I noticed there is a lot of confusion about what MVVM is and how to use it. Since I struggled through the maze of material online to figure out what MVVM is and how its used, I thought I’d try and write a simpler explanation. I hope this clarifies things a bit and doesn’t make it worse :)

Rate this:

Share this:

Like this:

LikeLoading...

Related

This entry was posted on Sunday, May 8th, 2011 at 2:24 am and is filed under MVVM. You can follow any responses to this entry through the RSS 2.0 feed.
You can leave a response, or trackback from your own site.

Post navigation

51 Responses to A Simple MVVM Example

I also would like to thank you! Am new to mvvm and wpf. Have a question regarding the models. Say I have a customer model with the following fields, FirstName, LastName, Address, Town, Country. On the form the last two fields Town and Country require their own table and need to be displayed in a combobox. Obviously the list of towns or countries is not part of the model, yet the comboboxes must appear on the same form but are not part of the model. Not sure how to deal with this with mvvm.

Hi Harry, typically the ItemsSource for that dropdown would bind to something other than the current data model, such as a static resource collection, or the a property on the DataContext on an item further up on the View.

I would like to say thank you! thank you!
I was looking for some example on how to navigate between views, but i can’t find a good example.
I’m having a hard time doing this mvvm thing but i find your blog easy to understand for beginners like me. :)
thank you!

Thanks for a great article, which help me getting up to speed implementing MVVM Pattern.

I consulted the prism MVVM online documentation(Developer’s Guide to Microsoft Prism Library 5.0 for WPF) chapter 5, the first figure illustrates the MVVM, in this diagram model is responsible for data as well as business logic (and validation). I thinks the ViewModel is just the glue between the UI and the Model. The Model represent the model in the real world(domain), and should contain data and business logic in my opinion.

It is just a pattern after all, I’m sure there is many views on how to implement it.

Hi Rachel. What you say about Models and ViewModels in the beginning of your article looks to me to sharply contradict what I’ve read elsewhere. It appears that either you or they have gotten the two mixed up. What I’ve read so far has it that the ViewModel is the one that “should only contain properties and property validation” and the Model is the one that contains all the business logic–the opposite of what you explain. Have I just missed something here?

Models are typically either plain data models (think of something like a database row), or they are domain models which represents the state of something at run time. They usually only contain properties and basic validation related to that single model object itself. They are the building blocks used by the rest of the code when constructing the application.

ViewModels are meant to be code representations of the Views. This means if the View needs a Name property, the ViewModel may contain a string property called Name, although that string property is probably stored on a Model inside the ViewModel. So although the ViewModel may contain the properties the View needs, it usually will be using a Model object to store those values. ViewModels also contain more advanced validation, such as checking if the user has access to something, or verifying that an item is unique.

It should be noted here that some people prefer to return the actual Model object to the view in its entirety, such as I have, rather than create separate properties on the ViewModel that get/set properties on the Model. This often is faster to code and more practical, although it is not the “MVVM purist” approach. Both methods are acceptable when using MVVM.

Very nice description of a simple MVVM, but I’m still confused. I’m *very* new to C# and WPF, having done mostly web-based applications.

I’m still confused as to how you are affecting changes with this pattern. I’ve gone through other tutorials describing this method and they seem to leave out the piece I’m not understanding.

When you change the ProductId from ‘0’ to ‘1’ the “Get Product” button becomes active. How? When you click on the “Get Product” button the ProductModel DataTemplate appears. How does it appear? The application works as described but I’m completely stumped as to the how.

It’s clear to me that when you change the data in the “TextBox”es an event is triggered, but just can’t see what else the delegates are doing.

When you bind a DependencyProperty in WPF, you are telling the property to look somewhere else to get it’s value instead of looking for the value locally on the object. So when you bind a TextBox.Text to a ProductId, you are telling WPF that it should go look at the ProductId property of whatever the TextBox’s data layer is anytime the Text property is needed. (I have a blog post about the data layer here if you’re interested in learning more about it)

Most bound objects implement the INotifyPropertyChanged interface, which WPF’s binding system uses to know when a bound value has changed and needs to be updated. For example, changing the ProductId from 0 to 1 will trigger a PropertyChanged notification for the ProductId property, and any bindings that rely on that value get automatically re-evaluated and updated.

The RelayCommand I am using for the Get Product button is a special type of command that automatically re-evaluates CanExecute() anytime a property changes, so when ProductId changes, the GetProductCommand re-evalutes it’s CanExecute method, which toggles the change of the button’s Enabled properties (Buttons that are bound to a Command will automatically bind their IsEnabled to the Command.CanExecute).

Clicking the button merely populates the CurrentProduct property, which is bound to a ContentControl’s Content property in the UI. When WPF receives notification that the CurrentProduct property has changed, it re-evaluates the binding and tries to draw the CurrentProduct object in the UI. Because I have an implicit DataTemplate defined in the Resources (A DataTemplate that has a Type, but not a Key), WPF will automatically use that DataTemplate when trying to draw an object of type Product.

Hope that helps clarify things, and that I didn’t just confuse you more =)

WPF actually evaluates Command.CanExecute when the control is first rendered, and that determines if the button is Enabled or not.

I don’t even think CanExecute is checked when you click on a Button that is bound to a Command, unless you perform the check manually.

The RelayCommand I used will re-evaluate CanExecute anytime a property change notification is raised, and that will alert any bindings to the command that they need to reevaluate.

There are other commands which behave differently. One example is Microsoft Prism’s DelegateCommand, which does not automatically re-evaluate the CanExecute when any property changes (this is better on performance). To use their command, you have to re-evaluate CanExecute manually when a property you’re interested in changes

Late to the MVVM game. Your work shared here is wonderful. I was in the middle of my own DataTemplate vs UserControl war. You (and one other) have convinced me, unless I have some unusual data presentation or needed extension, I should stick with DataTemplates. Love your by-line. You’ve certainly helped me understand.

The RelayCommand class uses delegates for Execute and CanExecute, so you can easily build Commands in your ViewModel without having to write a new command definition every time you want to add a Command to your ViewModel.

Rachel, great post. Tell me how you would handle this situation: You have another property in ProductModel, “bool OnSale”. In your view, you want to display “Yes” if OnSale=true and “No” if OnSale is false. What I’ve been doing is just making another property in the ProductModel called OnSaleDisplay which is a string with just a “get” and no “set”. This works well because I can raise a notification for OnSaleDisplay when OnSale changes (with an OnPropertyChanged(“OnSaleDisplay”) within the OnSale property.

However, after reading your post, I suspect OnSaleDisplay doesn’t belong in ProductModel. How would you do this and who is responsible?

Hi mrothaus, I would actually create a converter in the View that converts the boolean value to a Yes/No value since this seems like something only the View would care about, and the converter could be re-used in other places where you want to convert a boolean to a Yes/No value

Good work! I would just like to add that in my models, I _do_ have business logic, validation etc. The reason is that I can then use my models stand alone, e.g. in apps where there is no view. The model knows how to persist data, usually through a repository interface.

Rachel, thanks for a simple explanation of MVVM. The one thing that gets me thinking in circles are reusable controls and view models. For example, if we need to reuse a phone number control over and over again in different views with the same logic behind the control, do we create a view model for this?

I can see how this would work for events, but how about the data itself that it uses? Please share your thoughts.

I usually have two kinds of UserControls: Very generic ones with no ViewModel at all that get passed any values they need via DependencyProperties, and more complex UserControls that are built to go with a specific ViewModel, and that ViewModel is expected to be used as the DataContext when the UserControl is used.

I’m a bit unclear about where your PhoneNumber example would land since I’m not sure what sort of functionality you’re thinking a PhoneNumber would have.

If you want to use a UserControl as nothing more than a generic way to display the phone number, such as having 3 TextBoxes to separate out the phone number sections, then I’d probably do the first case of building a PhoneNumberUserControl and have a DependencyProperty for PhoneNumber that is a string that can be passed to the UserControl.

If you’re doing something more complex, such as supporting various phone number types like international numbers, extensions, etc, and adjusting the View based on the type of number it is, I’d probably build a PhoneNumberViewModel and build my UserControl with the expectation that the DataContext will be of type PhoneNumberViewModel. Then the actual application classes would have to use a PhoneNumberViewModel anywhere they want to represent a phone number, and the View would tell WPF to draw the PhoneNumberViewModel using the PhoneNumberUserControl.

I hope I understood your question correctly and didn’t confuse you more than you already were :)

WPF’s binding system listens for property change notifications (so a <TextBox Text=”{Binding SomeProperty}” /> will re-evaluate SomeProperty for the Text anytime it hears a PropertyChange notification where e.PropertyName == “SomeProperty”), and you can also hook your own handlers to the PropertyChange notifications and do some custom logic yourself anytime a property changes.

It is a good article and easy to understanding for beginner such as me. I am building a Windows phone application. I followed your article to create the class. However, I got the erorr during deserialization. The error is “The type ‘CMSPhoneApp.ObservableObject’ cannot be deserialized in partial trust because it does not have a public parameterless constructor.” Would you have any suggestion how can I solve it?

Good article although too much fluff eg:
RaisePropertyChanged(string propertyName) is never called so can be omitted and in the OnPropertChanged method there is no need to create a new handler reference, you could just use:if (PropertyChanged != null) {
var e = new PropertyChangedEventArgs(propertyName);
PropertyChanged(this, e);
}

In most of the apps we write at my company, we have views corresponding to instances of classes of the domain model. Therefore, we wrote a framework which makes it easy to use our domain model classes as ViewModels. We do this for all our views, except the apps main views (as stated in your article about navigation with ViewModels).
What do you think about this?
For instance, in the example you wrote above, what would you think about putting the relay commands directly into your model, and therefore using it as datacontext of your view?

Glad you enjoyed the article! There are many different frameworks or variations of MVVM, however I personally like to keep my Models as plain old data objects that only contain some raw data validation and PropertyChange notifications, and to put any application or business logic such as Command handlers in ViewModels.

I’ll still use Models sometimes as the DataContext for my Views, however I try and keep any application-related functionality out of them to keep the layers separate and make maintenance easier.

Hi Rachel,
I see this article is still read a lot :-) I have a new need for insight : How do you do when your Data Objects are modified by other threads? Do you manage dispatcher calls in your ViewModels, using CheckAccess or something similar?
Do you do it everytime, for example in your abstract ViewModel class, or do you specifically implement this for the ViewModels that will likely wrap multi-threaded-modified data models?

Thanks for this clear blog … I probably am going to convert my (too big) WPF app into a MVVM app. Till now, I only separated the Model and View, so the ViewModel logic is now shared between the Model and the View.

Hi Rachel, This is a great article, I just have one question. When you run this app, there is textbox validation going on. Where is that coming from. I cannot find textbox validation code anywhere. Thanks in advance.

Hi Mark, there is some default validation that is built into the default WPF Control Templates. For example, if a TextBox’s Text is bound to an int field, and the user enters some letters, it will cause an error since you cannot store text in an int field.

The default validation template is usually just a red border around the control, but this template can be modified. You can also modify the validation logic by making your class implement `IDataErrorInfo`.

Just a right time. I am planning to scale my old inventory application to a WPF app. and was looking for few easy samples on MVVM. Most of the MVVM explanation on the net uses very cryptic language that is hard to understand for beginners.

I think I’ve got a valid (no pun intended) problem with the code in the article.

I’m getting the err msg, “‘SimpleMVVMExample.Model.ProductModel’ does not contain a definition for ‘IsValid’ and no extension method ‘IsValid’ accepting a first argument of type ‘SimpleMVVMExample.Model.ProductModel’ could be found (are you missing a using directive or an assembly reference?)”

In the article, “IsValid” only appears once – on that line where I’m getting the err msg. What to do/how to solve this?

Sorry about that, my original sample had the Model’s implementing IDataErrorInfo and doing some validation. I left that out for simplicity, and forgot to remove the IsVaild reference. Thanks for catching that.