Wednesday, January 2, 2013

Once I started learning MVVM pattern for Windows Phone, I decided to write a short sample demonstrating all the features so that I can sum it up for myself. Here it is.
This article was a great starting point to understand MVVM. The most important thought I got out of that article was the INotifyProperty changed interface, which allows the controls on the phone be notified about the changes in the elements that they are bound to.
We'll start with the view:

The idea behind the app is very simple: there are two buttons, pressing one of them deactivates it and activates the other. It also changes the Content property of the other button. So my ViewModel should expose two properties for buttons' contents, two commands, and two properties for buttons' enabled/disabled status. Let's get to it. By the way, Random class will be my model, it will provide Content for buttons.

Not much to explain here, everything seems pretty obvious and simple. As I said before, the this.OnPropertyChanged(...) methods letting the View know that things change and the View adjusts accordingly.

A couple of points of interest. If your buttons don't seem like they are reacting to the commands and you think everything is hooked up properly, check to make sure your ViewModel class is declared as public.

This site has videos on MVVM implementation for more serious things like, navigation and so on.

Also, be sure to check out my other article on MVVM where I implement a simple keyboard on Windows Phone. That tutorial is easier than this one.

For another tutorial, be sure to check my other article on the subject.