Thursday, November 17, 2011

Binding To Collections

Most data binding scenarios involve lists – such as a list of employees or a list of products. For these scenarios its common to use the Silverlight ListBox control. The ListBox knows how to display a collection of items by replicating a data template for each item. A data template describes the controls you want to use when displaying each individual item in a collection. You can almost think of a data template as a mini-control because it contains a bunch of child controls. The ListBox simply creates one instance of this mini-control for each object in the model’s collection. An example is shown below.

<ListBox ItemsSource="{Binding}">     <ListBox.ItemTemplate>         <DataTemplate>             <TextBlock Text="{Binding Name}">TextBlock>         DataTemplate>     ListBox.ItemTemplate>                         ListBox> 

The ItemsSource property of the ListBox is the property that will reference the collection we want to databind. In this case we use the binding expression {Binding}, meaning we want the “whole” of the DataContext. In this scenario the model itself is a collection of objects. You could also drill into the model by with an expression such as {Binding Department.Employees}.

Notice the ItemTemplate of the list is set to a DataTemplate. Inside the DataTemplate is a single TextBlock to display the Name property of each object in the model. In this case we are using just a single TextBlock, but the powerful DataTemplate could include multiple controls, such as text blocks, images, videos, and colorful graphical elements. When the above XAML is combined with the code shown below, the result will be the image shown on the right.

var employees = new List<Employee>()image  {     new Employee { Name = "Scott" },     new Employee { Name = "Poonam"},     new Employee { Name = "Paul" } }; this.DataContext = employees; 

Quite often you’ll find data templates inside the resource section of a Page or application. The beauty of resources in Silverlight is that you can reuse resources across multiple pages in an application, and you also keep your XAML a little cleaner. Using such an approach with the above XAML would look like the following.

<UserControl.Resources>     <DataTemplate x:Key="employeeTemplate">         <TextBlock Text="{Binding Name}">TextBlock>     DataTemplate>       UserControl.Resources>      <ListBox ItemsSource="{Binding}"           ItemTemplate="{StaticResource employeeTemplate}"> ListBox> 

We can now reference the data template for displaying an employee by using the {StaticResource} binding and specifying a key of employeeTemplate. Although this template resource is only available inside of the same user control, we could take the template and place it in the resources section of the App.xaml file and reuse the template throughout the application.

No comments:

Post a Comment