Saturday, February 20, 2010

ObservableItemCollection Class

While working with WPF data binding I often found myself populating an ObservableCollection with instances of classes that implement INotifyPropertyChanged, and then subscribing the same method to the PropertyChanged event of each element. To eliminate such boilerplate code, I derived from ObservableCollection to create ObservableItemCollection. When the PropertyChanged event of any element of the the collection is raised, the ObservableItemCollection's own PropertyChanged event is invoked. Coincidentally Microsoft is planning on releasing a similar class with the same name.


using System;
using System.ComponentModel;
using System.Collections.Specialized;
using System.Collections.ObjectModel;

namespace ExploringDotNet
{
public class ObservableItemCollection<T> : ObservableCollection<T>
{
public event PropertyChangedEventHandler ItemPropertyChanged;

void Item_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (ItemPropertyChanged != null)
ItemPropertyChanged(sender, e);
}

protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null)
foreach (INotifyPropertyChanged i in e.NewItems)
i.PropertyChanged += Item_PropertyChanged;

if (e.OldItems != null)
foreach (INotifyPropertyChanged i in e.OldItems)
i.PropertyChanged -= Item_PropertyChanged;

base.OnCollectionChanged(e);
}
}
}

No comments:

Post a Comment