Getting notified when collection changes with ObservableCollection in C# .NET
December 6, 2016 1 Comment
Imagine that you’d like to be notified when something is changed in a collection, e.g. an item is added or removed. One possible solution is to use the built-in .NET generic collection type ObservableCollection of T which is located in the System.Collections.ObjectModel namespace. The ObservableCollection object has an event called CollectionChanged. You can hook up an event handler to be notified of the changes.
If you don’t know what events, event handlers and delegates mean then start here.
Let’s see a simple example with a collection of strings:
ObservableCollection<string> names = new ObservableCollection<string>(); names.Add("Adam"); names.Add("Eve"); names.Add("Clive"); names.Add("Anne"); names.Add("John"); names.Add("Peter"); names.Add("Hannah");
Nothing special so far I guess. This looks exactly like a “normal” collection.
The following example demonstrates the CollectionChanged event:
private static void RunObservableCollectionCode() { ObservableCollection<string> names = new ObservableCollection<string>(); names.CollectionChanged += names_CollectionChanged; names.Add("Adam"); names.Add("Eve"); names.Remove("Adam"); names.Add("John"); names.Add("Peter"); names.Clear(); } static void names_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { Debug.WriteLine("Change type: " + e.Action); if (e.NewItems != null) { Debug.WriteLine("Items added: "); foreach (var item in e.NewItems) { Debug.WriteLine(item); } } if (e.OldItems != null) { Debug.WriteLine("Items removed: "); foreach (var item in e.OldItems) { Debug.WriteLine(item); } } }
The NotifyCollectionChangedEventArgs object resides in the System.Collections.Specialized namespace.
If I run the RunObservableCollectionCode method I get the following output:
Change type: Add
Items added:
Adam
Change type: Add
Items added:
Eve
Change type: Remove
Items removed:
Adam
Change type: Add
Items added:
John
Change type: Add
Items added:
Peter
Change type: Reset
You can then decide how to handle additions and deletions in the event handler.
View all various C# language feature related posts here.
Good one (y)