PETZOLD BOOK BLOG

Charles Petzold on writing books, reading books, and exercising the internal UTM


Recent Entries
< PreviousBrowse the ArchivesNext >
Subscribe to the RSS Feed

My Article on Property-Changed Notifications in MSDN Magazine

September 7, 20098
New York, NY

I received the print edition of the September 2008 issue of MSDN Magazine in the mail yesterday; the contents will go online later this month. My quarterly contribution to the Foundations column is an article on WPF programming entitled "Dependency Properties and Notifications" which includes two ObservableCollection<T> derivatives that attach property-changed event handlers on items in the collection.

These two classes — named ObservableNotifiableCollection<T> and ObservableDependencyObjectCollection<T> — both contain the same flaw. The classes work by overriding the OnCollectionChanged method; property-changed event handlers are attached for items being added to the collection, and these handlers are detached for items being removed from the collection.

The problem is the Clear method: When the collection is cleared, the OnCollectionChanged is called with a NotifyCollectionChangedEventArgs argument with an Action property of NotifyCollectionChangedAction.Reset. However, the OldItems property is null in this case, and the items have already been removed from the collection. The property-changed event handlers will not be properly detached from the removed items.

The fix is fairly simple: Override the ClearItems method and detach the event-handlers at that time. In ObservableNotifiableCollection<T> the code is:

and in ObservableDependencyObjectCollection<T> the code is:


Comments:

very nice holmes

Chingo.NET, Fri, 12 Sep 2008 00:29:16 -0400 (EDT)

?? September 7, 2009 ?? Back to the future with .Net...

poc, Sat, 13 Sep 2008 17:08:15 -0400 (EDT)


Recent Entries
< PreviousBrowse the ArchivesNext >
Subscribe to the RSS Feed

(c) Copyright Charles Petzold
www.charlespetzold.com