- Design Pattern Versus Framework
- MVVM Prerequisite: Data Binding
- INotifyPropertyChanged
- The Model
- The View
- The ViewModel
- Summary
INotifyPropertyChanged
A data binding simply provides the mechanism to attach a user-defined object to a DependencyObject that is most likely a UI element defined in XAML. Figure 1 illustrates this relationship: where the data binding exists and how it works with the previous example.
Figure 1 Data binding
The mode here is one-way (the default mode in Silverlight) so the source data updates the target DependecyProperty and the binding is done. Data binding can also perform a two-way binding that allows the DependencyProperty to update the corresponding property on the class. This is useful when binding text fields to text boxes, because the user may input text and the data binding will then update that text to the corresponding text field.
The reverse is also true: A change to the underlying class, or the data-binding source, can cause changes in the UI. In order for this to happen, the data binding must be informed when the value of a property changes. It “listens” for this change. When it occurs, it will update the corresponding DependencyProperty with the new value. To notify a data binding of a property change, the source object must implement the interface named INotifyPropertyChanged.
The following classes shown in Figure 2 in System.dll facilitate property change notification.
Figure 2 INotifyPropertyChanged
The interface simply defines an event that provides a handler for the property change notification. The event arguments include the name of the property that changed. It is the implementation of this interface that is fundamental to the MVVM, pattern because it provides the necessary notification for data binding to work. The following code shows how the interface is implemented. Note that the property implements a backing field and raises the notification whenever the value changes:
A local variable is used to refer to the handler and then checked before raising the event. This pattern is implemented to avoid the very rare case of the handler being unhooked by another process during the setter call. This would cause an exception when raising the event directly, so the handler is copied first. If it is unhooked, the code will still execute it one last time and then subsequent calls will evaluate to null and avoid the call.
The MVVM pattern was created to take advantage of data binding and provide services around property change notification. The pattern itself strives to separate concerns by keeping the application data and business logic completely independent of the user interface. This is accomplished via the three components of MVVM: the model, the view, and the view model.