In the previous post I mentioned that the view’s bounded controls can be updated automatically when the view model’s properties to which they are bounded changes, given that the view model raises a specific event. In this post I want to elaborate on that, and walk you through the relevant implementation in Kona.
The INotifyPropertyChanged Interface
To provide change notification to the view’s data bound controls, the view model should implement the INotifyPropertyChanged interface, which contains a single event called PropertyChanged, and raise that event whenever a property changes.
The following example shows how the PropertyChanged event is raised whenever the FirstName and LastName property changes:
As with the ICommand interface, most of the code involved in implementing the INotifyPropertyChanged interface is duplicate. Moreover, it is error-prone, as the changed property’s name is passed as a string literal.
The BindableBase Class
Kona solves both the code duplication and the string literal problems with the BindableBase abstract class, which implements the INotifyPropertyChanged interface and provides the SetProperty<T> method for a much cleaner ‘set’ methods. Here is the same view model as above, refactored to derive from the BindableBase class:
By using the SetProperty<T> method, we reduced the properties’ set method to one line. The underlying member is passed as a ref parameter to allow the SetProperty<T> method to update its value.
You are probably wondering how the changed properties’ name is determined. Those of you who used Prism, remember that Prism’s NotificationObject avoided passing the property name as a string literal, by parsing an Expression object at runtime. Kona, which is built against the .NET 4.5 Framework, takes advantage of the new CallerMemberName attribute. This attribute is evaluated at compile time and therefore has no performance costs.
Usually, the view model will not inherit directly from the BindableBase class. Instead, it will inherit from the ViewModel class which extends the BindableBase class by adding methods for state management. These methods are being used when the user navigates through the app, and will be discussed in a future post about navigation in Kona.
Next time: Deep dive into the ViewModelLocator class.