Sunday, December 11, 2011

Silverlight: Data Binding

In this article, I am going to explain basic concepts of data binding in Silverlight applications. I will also cover different types of binding modes available in Silverlight. We will cover how to use it declaratively and programmatically.

DATA BINDING
Data binding is the mechanism to display related data available in object (Model) into UI controls(View) and facilitate user to add,change it. Binding includes expressions, data templates, converters, binding modes, and validation.



Binding Expression
It is generally an expression within curly braces '{}' that is used to map property of an object (Model) to UI control (View) inside XAML page.

<StackPanel>
        <TextBlock Text="{Binding Name}" />
        <TextBlock Text="{Binding Path=ID}" />
        <TextBlock Text="{Binding Department.Name}"/>
</StackPanel>
 

The first TextBlock in the above XAML is using a binding expression on its Text property.
The binding expression take the value for this Text property from the Name property of the model.
The second TextBlock is fetching the ID property of the model using a another but equivalent binding expression (the Path word is optional in simple expressions).
It can even navigate an object hierarchy as mentioned in the third TextBlock. In this it will find a Department
property on the model, then fetch the Name property from that object and use that for the Text property.


Data Context
Most Silverlight controls exposes DataContext property. By setting this property controls are notified to use object as model. Thus, the following C# code, combined with the above XAML, will produce the display shown below:
Employee objEmployee = new Employee()
{
    Name = "Durgesh",
    ID = 1,
    Department = new Department() { Name = "Engineering" }
};
this.DataContext = objEmployee;