Data binding in Silverlight

13Oct10

One of the most compelling features of Microsoft Silverlight is the ability to display data in a rich and dynamic grid view. This grid view shares many features of its big siblings over in ASP.NET, but there are some differences to watch out for. I’m going to focus on one difference that affected me in a recent project in order to focus this post and keep things short.

There is no DataSet in Silverlight

What, you ask, how can we do advanced data binding without DataSets? I asked the same thing, but the answer lies in the .NET Framework 4’s ObservableCollection. System.Collections.ObjectModel.ObservableCollection provides a notification interface in the form of events that are raised when items are added or removed from the list. This allows the Silverlight GridView UI to stay updated when the underlying data changes.

In order to create a bindable data structure, I created a POCO (plain old C# object) that had the fields I wished to display like so:

	public class Product
	{
		public string name { get; set; }
		public string productid { get; set; }
		public string price { get; set; }
               ...
      }

Once we have a class to represent the list items, we instantiate the generic list using the new type:

ObservableCollection<Product> itemsource = new ObservableCollection<Product>();

The ObservableCollection supports all list operations, so building the list works just like any other IList:

itemsource.Add( new Product() );

Finally we can bind the new collection to the grid as follows:

dataGrid.ItemsSource = itemsource;

This is just the tip of the iceberg with databinding in Silverlight. In a forthcoming post I’m going to show how Silverlight supports binding to nested collections.

Advertisements


No Responses Yet to “Data binding in Silverlight”

  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: