Working with Observable Collections in Silverlight

Observable Collections are great to preserve the latest data in data controls without having to rebind data to the data controls. In this article we will explore how we can work with Observable Collections in Silverlight 5.

Pre-requisites

As of this writing, Silverlight 5 has been released. To execute the code examples illustrated in this article, you should have the following installed in your system:

  • Visual Studio 2010

Silverlight – A Quick Look

Silverlight is a browser plug-in that promotes a collaborative development environment of rich online media content that enables developers and designers alike to integrate multimedia and graphics into web pages within the context of the managed environment. Over the past few years, Silverlight, formerly known as Windows Presentation Foundation Everywhere (WPF/E), has become popular worldwide for developing the next generation of cross-browser, cross-platform Rich Internet Applications (RIAs).

Observable Collections

The generic List<T> represents a strongly typed list of elements or a CLR or non-CLR type. When we bind data to a DataControl in ASP.NET using such a list, the data in the data bound control is up to date with the data in the list. However, when the data in the list changes, the data control has to be re-bound to reflect the changes. In other words, we have to rebind the data in the list (now the list contains updated data) to reflect the change. This problem is solved in using ObservableCollection<T>. This collection is capable of providing notifications of items added/deleted/edited through the INotifyCollectionChanged interface. The INotifyCollectionChanged interface has an event called PropertyChanged, which is fired when a property value is changed.

ObservableCollection is a generic dynamic data structure that has the ability to send notifications when items are added, removed or when the collection is refreshed. The MSDN states: "Represents a dynamic data collection that provides notifications when items get added, removed, or when the whole list is refreshed." Reference: http://msdn.microsoft.com/en-us/library/ms668604.aspx

The ObservableCollection class is shown below:

[SerializableAttribute]
public class ObservableCollection<T> : Collection<T>, 
            INotifyCollectionChanged, INotifyPropertyChanged

You can instantiate an Observable collection as shown in the code snippet below:

using System.Collections.ObjectModel;
ObservableCollection<Product> products = new ObservableCollection<Product>();

Consider the following class:

public class Contact
    {
        private string firstName;
        private string lastName;
        private string address;
 
        public Contact(string firstName, string lastName, string address)
        {
            this.firstName = firstName;
            this.lastName = lastName;
            this.address = address;
        }
 
        public string FirstName
        {
            get { return firstName; }
            set { firstName = value; }
        }
 
        public string LastName
        {
            get { return lastName; }
            set { lastName = value; }
        }
 
        public string Address
        {
            get { return address; }
            set { address = value; }
        }
    }

The following class creates an Observable Collection out of the Contact class:

public class EmployeeList : ObservableCollection<Contact>
    {
        public EmployeeList()
            : base()
        {
            Add(new Contact("Joydip", "Kanjilal", "Hyderabad"));
            Add(new Contact("Debanjan", "Banerjee", "Kolkata"));
            Add(new Contact("Shaik", "Tajuddin","Hyderabad"));
            Add(new Contact("Firdous", "Khan", "Hyderabad"));
        }
    }

You can now use the Observable Collection you have created to bind data to a Silverlight Data Grid. Here is how the mark-up code would look:

<Grid x:Name="LayoutRoot" Background="White">
        <sdk:DataGrid x:Name="dgData" Grid.Row="2" AutoGenerateColumns="True"  ItemsSource="{Binding Source}" >
 
        </sdk:DataGrid>
    </Grid>
 
 

And, here's the code you would write to bind data to the DataGrid control named dgData:

public partial class MainPage : UserControl
    {
        EmployeeList empList = new EmployeeList();
 
        public MainPage()
        {
            InitializeComponent();
            
            dgData.ItemsSource = empList;
 
        }
    }
 
 

To ensure that the DataGrid is refreshed if any item in the collection is changed, we should take advantage of the PropertyChangedEventHandler event handler. The NotifyPropertyChange event handler would be automatically called whenever the list is changed.

  public event PropertyChangedEventHandler PropertyChanged;
 
        protected void NotifyPropertyChange(string propertyName)
        {
 
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
 
        }

The complete source code is given below for reference:

public partial class MainPage : UserControl
    {
        EmployeeList empList = new EmployeeList();
 
        public MainPage()
        {
            InitializeComponent();            
            dgData.ItemsSource = empList;
 
        }
 
        public EmployeeList Data
        {
 
            get { return empList; }
 
            set
            {
 
                empList = value;
 
                NotifyPropertyChange("empList");
 
            }
 
        }
 
        public event PropertyChangedEventHandler PropertyChanged;
 
        protected void NotifyPropertyChange(string propertyName)
        {
 
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
 
        }
    }
 

Suggested Readings

http://www.jigar.net/articles/viewhtmlcontent328.aspx

http://www.microsoft.com/silverlight/

http://www.codeproject.com/Articles/42536/List-vs-ObservableCollection-vs-INotifyPropertyCha

http://weblogs.asp.net/joelvarty/archive/2008/11/17/silverlight-databinding-the-observable-collection.aspx

Summary

In this article we discussed how we can work with Observable Collections in Silverlight 5. We explored Observable Collections, why they are helpful and how we can bind data to data controls in Silverlight using Observable Collections. Happy reading!



Related Articles

Comments

  • Almost Worthless Information

    Posted by Dempsey on 09/30/2012 08:09pm

    I found this information so vague and non-instructive as to be almost totally useless. I wish you had thought to include a more complete discussion and example. But thanks for trying. Dempsey

    Reply
  • Working with images

    Posted by gabeV on 08/03/2012 02:16pm

    Thanks for this tutorial, it was very helpful. I was trying to do something very similar, except I was trying to see if I could add an image value to the class and add multiple image files to the collection. However, when I go to add the image type the collection doesnt seem to accept it. Not sure if you've tried this and can assist me with it. Thanks again.

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • This paper introduces IBM Java on the IBM PowerLinux 7R2 server and describes IBM's implementation of the Java platform, which includes IBM's Java Virtual Machine and development toolkit.

  • As mobile devices have pushed their way into the enterprise, they have brought cloud apps along with them. This app explosion means account passwords are multiplying, which exposes corporate data and leads to help desk calls from frustrated users. This paper will discover how IT can improve user productivity, gain visibility and control over SaaS and mobile apps, and stop password sprawl. Download this white paper to learn: How you can leverage your existing AD to manage app access. Key capabilities to …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds