One of the nice things of the latest versions of .net, is the ObservableCollection<T>. This class implements the new INotifyCollectionChanged interface (similar to INotifyPropertyChanged that we all know). Here is a small code example:
1 [TestMethod]
2 public void ObservingAReadOnlyObservableCollectionSucceeds()
3 {
4 //setup original collection with some initial content;
5 ObservableCollection<string> strings = new ObservableCollection<string>();
6 strings.Add("string1");
7 strings.Add("string2");
8
9 //setup readonly collection
10 ReadOnlyObservableCollection<string> readOnlyStrings = new ReadOnlyObservableCollection<string>(strings);
11 int addedElementsWhileObservingReadOnlyCollection = 0;
12
13 //setup observer
14 (readOnlyStrings as INotifyCollectionChanged).CollectionChanged += delegate(object sender, NotifyCollectionChangedEventArgs e)
15 {
16 if (e.Action == NotifyCollectionChangedAction.Add)
17 {
18 addedElementsWhileObservingReadOnlyCollection += e.NewItems.Count;
19 }
20 };
21
22 //add one item, addign should be observed
23 strings.Add("addedString");
24
25 //assert
26 Assert.AreEqual(3, readOnlyStrings.Count);
27 Assert.AreEqual(1, addedElementsWhileObservingReadOnlyCollection);
28 }
Notice the usage of ReadOnlyObservableCollection<T>, which can be used when you don't want someone to alter the contents of a collection.
These are the problems we see with all this new goodness:
- These types reside in the WindowsBase.DLL assembly with weird innapropriate namespaces.
- ReadOnlyObservableCollection<T> and ObservableCollection<T> implement INotifyPropertyChanged explicitly, meaning you have to cast to INotifyPropertyChanged to be able to use notifications.