Wednesday 12 May 2010

Silverlight and the ObservableCollection<T> class

The ObservableCollection<T> class can be used to represent dynamic data collections. It provides notifications when items are added or removed from the collection as well as when the entire collection is refreshed.

This class can be used in data binding scenarios so that insertions or deletions in the collection can update the UI automatically.

The dynamic behaviour is achieved through the implementation of the INotifyEventChanged interface that exposes a CollectionChanged event.

Note there are potential issues with thread safety:

“Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.” - http://msdn.microsoft.com/en-us/library/ms668604%28VS.95%29.aspx

Your domain classes need to implement the INotifyPropertyChanged interface. This interface requires the implementing class raise a PropertyChanged event whenever the state of the object changes. Note this applies to WFP as well as Silverlight.

See also:

INotifyPropertyChanged - http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged%28v=VS.95%29.aspx

Wednesday 12 May 2010