Implementing Model-View-ViewModel (MVVM) in Windows Phone

Model-View-ViewModel (MVVM) is a solid presentation model and the best benefit of this design is that it lets you decouple UI and logic which makes you unit test your logic easily. You will find a lot of stuff over the internet about MVVM but I am going to quickly introduce you using a diagram:

Source: Implementing MVVM (Microsoft Patterns & Practices)

The View in case of Windows Phone is the UI page (.xaml) and code behind (.cs/.vb). Model is plain data model. ViewModel contains presentation logic which may encapsulates models, have some logic around it, interact with repositories etc. View and ViewModel are connected via Binding or Commands etc. I will cover those as we code it.

In this post, I am going to share a very naive way of implementing MVVM to develop your apps on Windows Phone but more or less we can implement MVVM same way to develop Windows Store apps. In fact in my upcoming post I would love to write about how we can share code between Windows Phone and Windows Store apps by implementing MVVM + Portable Libraries + Dependency Injection.

Microsoft XAML based solutions supports MVVM as most of basic components required to implement MVVM are baked in as part of framework e.g. DataContext and Binding, INotifyPropertyChanged, Commands etc. I will get back to these terms as we go through code.

So here is something we are going to develop. A simple app with contact page allow user to fill in name, email, select a category, add details to it and submit it. We would add some basic validation here as well.

Contact Form Sketch

So let’s jump to code and start learning MVVM by writing code.

We will start by creating model first. I am gonna add a Category class which we would use to create a collection to populate categories.

Now there are couple of things here that needs explanation. INotifyPropertyChanged and OnPropertyChanged being called in setters. INotifyPropertyChanged is an interface that ships with framework and the class implements it is able to notify their view/clients that a property value has changed. So once we bind our view with ViewModel/Model then we need a mechanism to inform View/UI that a value has been updated. What happens is that when we change value of a property in model it send raises property change event, which is why we are calling “OnPropertyChanged” method, to let view know that a property value has change and therefore please update your UI. And that’s the major purpose of INotifyPropertyChanged interface and we need to implement it in all Models or ViewModels which we intend to bind.

Now let’s create a view model. ViewModels are usually one per view, page in this case. So we are going to create ContactPageViewModel

We have an ObservableCollection<Category> which we would use to populate category list. The ObservableCollection is part of framework and it automatically notifies UI when an item has been added, deleted etc. We also have another property “SelectedCategory” which we would use to populate the selected property by the user. We have Name/Email for user data, Inquiry string for details and IsValid property that we would use for required validation.

Let’s talk about view now. Now here is a part that is kind of easier on Windows Platform such as Windows Store and Windows Phone in contrast to Android and iOS.

So binding a property of control is simple we use special XAML syntax “{Binding PropertyName, Mode = OneWay/TwoWay/OneTime}”. The mode here specify that whether binding would be one way i.e. from Model -> UI or TwoWay i.e. UI -> Model and vice versa. The other important thing to notice is Command. Commands are way to connect view events with ViewModel. In this case, we have registered submit button with SubmitCommand on ViewModel which would eventually call OnSubmit action.

BUT the potential of MVVM can be observed with how validation is handled. What I have done is that submit button will only be enable when IsValid property is true. And who is updating IsValid property? RequiredFieldValidator.
That’s why we have registered TextChanged event in UI which triggers source to update on every key stroke which update the ViewModel property which internally raises PropertyChanged event and that event is being handled by validator which sets IsValid to true all required fields are being populated.

And you just made a simple implementation of MVVM on Windows Phone. Please note that the above code is not production optimized. Also there are different ways to implement MVVM and this is just one way to do it. Also MVVM may not fit to very simple 1-2 pages app however the more complex the app the more likely it is that MVVM is the right fit for your app.

Sample code can be forked or downloaded from Github: https://github.com/adilmughal/DemoMvvm.WP