MVVM Prerequisite: Data Binding
The key feature that makes MVVM a viable pattern for Silverlight applications is the rich support for data binding. Data binding provides a way for Silverlight applications to both display and update data. It allows for separation between presentation and the way data is managed. The data binding provides a connection between underlying data and the presentation layer. It includes advanced features such as updating the underlying data in response to user input and automatically refreshing the display when the underlying data changes.
Silverlight provides a special type of class to help facilitate data binding. This base class is known as a DependencyObject. A DependencyObject is simply a container for special properties that participate in what is referred to as the dependency property system. A DependencyProperty is a special property that can be set in multiple ways including styling, data binding, animations, and inheritance. The influence of multiple sources helps determine the value of a DependencyProperty.
A DependencyProperty can be influenced in the following order (the first items take precedence over later items in the list):
- Active animations (Storyboard element)
- Local value (set in XAML), either value or data binding
- Template properties
- Implicit style
- DependencyProperty metadata
The following XAML illustrates value precedence:
When the application is run, it will always display a purple square because the storyboard animation has the highest precedence. In the designer, the square will appear in red due to the value of the data binding. The ColorProvider class simply returns a red brush:
When you remove the data binding, the rectangle turns blue as explicit style binding takes precedence. If you then remove the style property, the rectangle will turn green due the implicit style definition.