Anup Shah on WPF and Silverlight (Programming Garden)

IT 's For You!!!

Wednesday, February 1, 2012

DataContext


WPF provides a simple and powerful way to auto-update data between the business model and the user interface. This mechanism is called DataBinding. Everytime when the data of your business model changes, it automatically reflects the updates to the user interface and vice versa. This is the preferred method in WPF to bring data to the user interface.

Databinding can be unidirectional (source -> target or target <- source), or bidirectional (source <-> target).

The source of a databinding can be a normal .NET property or a DependencyProperty. The target property of the bindingmust be a DependencyProperty.

To make the databinding properly work, both sides of a binding must provide a change notification that tells the binding when to update the target value. On normal .NET properties this is done by raising the PropertyChanged event of theINotifyPropertyChanged interface. On DependencyProperties it is done by the PropertyChanged callback of the property metadata

Databinding is typically done in XAML by using the {Binding} markup extension. The following example shows a simple binding between the text of a TextBox and a Label that reflects the typed value:

Every WPF control derived from FrameworkElement has a DataContext property. This property is meant to be set to the data object it visualizes. If you don't explicity define a source of a binding, it takes the data context by default.

The DataContext property inherits its value to child elements. So you can set the DataContext on a superior layout container and its value is inherited to all child elements. This is very useful if you want to build a form that is bound to multiple properties of the same data object.


ValueConverters

If you want to bind two properties of different types together, you need to use a ValueConverter. A ValueConverter converts the value from a source type to a target type and back. WPF already includes some value converters but in most cases you will need to write your own by implementing the IValueConverter interface.

A typical example is to bind a boolean member to the Visibility property. Since the visibility is an enum value that can be Visible, Collapsed or Hidden, you need a value converter.



The following example shows a simple converter that converts a boolen to a visibility property. Note that such a converter is already part of the .NET framework.


 


-> you can derive your value converter from MarkupExtension and return its own instance in the ProvideValueoverride. So you can use it directly without referencing it from the resources.

-> When you get the error "No constructor for type '...' has 0 parameters.", you need to add an default constructor to your converter, even it's not needed. Just for the WPF designer.


No comments:

Post a Comment