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:
-
protected override void ClearItems()
{
foreach (INotifyPropertyChanged item in Items)
item.PropertyChanged -= OnItemPropertyChanged;
base.ClearItems();
}
and in ObservableDependencyObjectCollection<T> the code is:
-
protected override void ClearItems()
{
foreach (DependencyObject obj in Items)
foreach (DescriptorWrapper descriptor in descriptors)
descriptor.RemoveValueChanged(obj);
base.ClearItems();
}