List vs ObservableCollection

2011-08-22


Most of time we bind a collection of data to a ListBox or DataGrid in Silverlight or WPF, the 1st class for data is List class. But the problem if using List class is that List does not have built-in change notifications for the collection.

So if the data collection keeps changing, for update DataGrid or Listbox dynamically, we should not use List class but use ObservableCollection class. The ObservableCollection class represents a collection of dynamic data that provides built-in notification when items in the collection are added , removed, or refreshed.

The following content from MSDN:

(WPF provides the ObservableCollection<T> class, which is a built-in implementation of a data collection that implements the INotifyCollectionChanged interface.)

To fully support transferring data values from binding source objects to binding targets, each object in your collection that supports bindable properties must implement an appropriate property changed notification mechanism such as the INotifyPropertyChanged interface.

MSDN provides the following sample code:

public class NameList : ObservableCollection<PersonName>
{
    public NameList() : base()
    {
        Add(new PersonName("Willa", "Cather"));
        Add(new PersonName("Isak", "Dinesen"));
        Add(new PersonName("Victor", "Hugo"));
        Add(new PersonName("Jules", "Verne"));
    }
  }

  public class PersonName
  {
      private string firstName;
      private string lastName;

      public PersonName(string first, string last)
      {
          this.firstName = first;
          this.lastName = last;
      }

      public string FirstName
      {
          get { return firstName; }
          set { firstName = value; }
      }

      public string LastName
      {
          get { return lastName; }
          set { lastName = value; }
      }
  }

Then in .xaml file you can use above class for DataGrid:

this.grdData.ItemsSource = new PersonName();