Friday 6 June 2014

ViewModel Properties (1 of 3)

My previous post discussed using a Controller in conjunction with the standard MVVM pattern. One of the reasons for this approach is to simplify/clean the ViewModel. Another way I've found to do this is by using a class that represents a ViewModel property. Quite often when binding to a property on your ViewModel you require the property, whether it's enabled, whether it's been updated, it's visibility, etc. What if you could abstract all of this into a simple and easy to use class. Enter the ViewModelProperty (I know, not the most creative name).


As you can see this provides us with the Value, a formatted version of the value (if a format was set), validation, visibility and editability. It also removes the need to inherit from INotifyPropertyChanged in every ViewModel (although I guess you may still need to for other reasons). It's encapsulated everything into a single class.

I've also incorporated a Builder class and a Collection class. The Builder allows the user to create a property in a fluent manner (looks very pretty in code) and the Collection allows the ViewModel to view and act on all the ViewModel properties that are created. For example, let's say you want to reset all changes made to the properties, you could simple call ResetValues() on the Collection and it will do all the hard work by resetting each property instead of you having to manage it. Or you could very quickly check the validity of all the updates to your ViewModel properties through the IsValid property on the Collection.

You can view all the code here.

No comments:

Post a Comment