ObservableCollection is a .NET collection class that sends event notifications when items are added, removed, replaced, moved, or reordered in the collection, or when the entire contents of the collection are replaced.
ObservableCollection is an implementation of the Observer Pattern specifically to notify when the contents of a collection of items changes. It implements the INotifyCollectionChanged
interface which defines a CollectionChanged
event property.
Listeners can subscribe to the CollectionChanged
event to be notified when items are added, deleted, replaced, moved, or reordered within the collection or when the entire contents of the collection is replaced.
ObservableCollection
also implements INotifyPropertyChanged
and its PropertyChanged
event, but this event only fires when properties of the collection object change, not when properties of the items in the collection change. If you want to be notified when any property of any item in the collection is changed, you have to hook the PropertyChanged
event of every item as it is inserted into the collection. This can be done in a CollectionChanged
event handler.
Notes on XAML Usage
ObservableCollection<T>
can be used as a XAML
object element in Windows Presentation Foundation (WPF), in versions 3.0 and 3.5. However, the usage has substantial limitations.
ObservableCollection<T>
must be the root element, because the x:TypeArguments
attribute that must be used to specify the constrained type of the genericObservableCollection<T>
is only supported on the object element for the root element.
You must declare an x:Class attribute (which entails that the build action for this XAML file must be Page or some other build action that compiles the XAML).
ObservableCollection<T>
is in a namespace and assembly that are not initially mapped to the default XML namespace. You must map a prefix for the namespace and assembly, and then use that prefix on the object element tag for ObservableCollection<T>
.
A more straightforward way to use ObservableCollection<T>
capabilities from XAML in an application is to declare your own non-generic custom collection class that derives from ObservableCollection<T>
, and constrains it to a specific type. Then map the assembly that contains this class, and reference it as an object element in your XAML.