Register Login

 

Welcome to the Coach Factor blog. Here you will find all of our ideas on software development. Subscribe at  http://blog.nventive.net.

# Monday, September 22, 2008

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:

  1. These types reside in the WindowsBase.DLL assembly with weird innapropriate namespaces.
  2. ReadOnlyObservableCollection<T> and ObservableCollection<T> implement INotifyPropertyChanged explicitly, meaning you have to cast to INotifyPropertyChanged to be able to use notifications.
Monday, September 22, 2008 5:48:40 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
.net
Search
Archive
<September 2008>
SunMonTueWedThuFriSat
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011
Statistics
Total Posts: 47
This Year: 0
This Month: 0
This Week: 0
Comments: 2
Sign In