Tuesday 10 June 2014

ViewModel Properties (2 of 3)

It's time now to go over an example of how we could use our funky new ViewModel Properties. I've created a very simple Person example. In fact it's so simple you'll have to forgive me. There is no dependency injection and I'm creating a ViewModel in code behind, but it's all just to get the point across.


Lets look at PersonViewModel (or the start of it as seen above). You'll see on line 13 I'm creating an instance of the Collection. Then lines 15 to 20 are the Property definitions. And then at the bottom the constructor takes the Controller as a parameter and calls Initialse. All very clean and easy. So what happens in Initialse?


This is where the fun begins. We're creating all of our properties and specifying their behaviors. Lets look at Age (line 47) as a good example. The New method has to specify Name and the default "getter". This is the bare minimum. Next we add a description which can be used (and is in the example code) for binding to a TextBlock, then we set it to not be editable and we specify the format. And finally we call the Build method to return the built ViewModel Property.

Now how would the binding work?


PersonView is very simple, just a few TextBlocks and TextBoxes binding to our ViewModel Properties. You can see that all the TextBlock "labels" bind very nicely to the description of the Property. You can also see that each TextBox binds very nicely to the Value of our Property or in the case of Age to the FormattedValue of our Property. It can also very easily be made ReadOnly by binding to IsEditable (although you do need a converter that inverts the value). For fun I've also added something to display when City or occupation are updated and when they're invalid.

As (I hope) you can see the xaml becomes nice and clean and declarative, as it rightly should be. There are no string literals in the xaml because we're binding everything to our ViewModel, including any labels. The ViewModel completely defines the View.

I really like this approach because it seems to make everything that little bit neater. It appeals to the OCD in me. But in my opinion the greatest advantage to this approach will be addressed in my next post: testing.

P.S. You may have noticed that I haven't mentioned anything about the Commands in the ViewModel. They're using a similar approach I'm just not going into them to keep the post lighter. But feel free to take a look at it in the code.

You can view all the code here.

No comments:

Post a Comment