CHAPTER 9 COLLECTIONS AND GENERICS
Table 9-7. Useful Members of System.Collections.ObjectModel
System.Collections.ObjectModel
Type
Meaning in Life
ObservableCollection
Represents a dynamic data collection that provides notifications
when items get added, removed, or when the whole list is
refreshed.
ReadOnlyObservableCollection
Represents a read-only version of ObservableCollection.
The ObservableCollection class is very useful in that it has the ability to inform external objects
when its contents have changed in some way (as you might guess, working with
ReadOnlyObservableCollection is very similar, but read-only in nature).
Working with ObservableCollection
Create a new Console Application named FunWithObservableCollection, and import the
System.Collections.ObjectModel namespace into your initial C# code file. In many ways, working with
the ObservableCollection is identical to working with List, given that both of these classes
implement the same core interfaces. What makes the ObservableCollection class unique is that this
class supports an event named CollectionChanged. This event will fire whenever a new item is inserted, a
current item is removed (or relocated), or if the entire collection is modified.
Like any event, CollectionChanged is defined in terms of a delegate, which in this case is
NotifyCollectionChangedEventHandler. This delegate can call any method that takes an object as the first
parameter, and a NotifyCollectionChangedEventArgs as the second. Consider the following Main()
method, which populates an observable collection containing Person objects and wires up the
CollectionChanged event:
class Program
{
static void Main(string[] args)
{
// Make a collection to observe and add a few Person objects.
ObservableCollection people = new ObservableCollection()
{
new Person{ FirstName = "Peter", LastName = "Murphy", Age = 52 },
new Person{ FirstName = "Kevin", LastName = "Key", Age = 48 },
};
// Wire up the CollectionChanged event.
people.CollectionChanged += people_CollectionChanged;
}
static void people_CollectionChanged(object sender,
System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
throw new NotImplementedException();
}
347