Skip to content

Instantly share code, notes, and snippets.

@MatthewBarker
Created April 17, 2015 13:05
Show Gist options
  • Save MatthewBarker/5074a7b8a4312ee08627 to your computer and use it in GitHub Desktop.
Save MatthewBarker/5074a7b8a4312ee08627 to your computer and use it in GitHub Desktop.
Observes changes to properties on underlying items as well as the collection itself
namespace ViewModels
{
using System;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
/// <summary>
/// Represents an observable item collection.
/// </summary>
/// <typeparam name="T">The type of the item</typeparam>
public class ObservableItemCollection<T> : ObservableCollection<T> where T : INotifyPropertyChanged
{
/// <summary>
/// Initializes a new instance of the <see cref="ObservableItemCollection{T}"/> class.
/// </summary>
public ObservableItemCollection()
: base()
{
this.CollectionChanged += this.OnCollectionChanged;
}
/// <summary>
/// Called when item property changed.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="propertyArgs">The <see cref="PropertyChangedEventArgs"/> instance containing the event data.</param>
private void OnItemPropertyChanged(object sender, PropertyChangedEventArgs propertyArgs)
{
NotifyCollectionChangedEventArgs collectionArgs = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset);
this.OnCollectionChanged(collectionArgs);
}
/// <summary>
/// Called when collection changed.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="collectionArgs">The <see cref="NotifyCollectionChangedEventArgs" /> instance containing the event data.</param>
private void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs collectionArgs)
{
if (collectionArgs.OldItems != null)
{
foreach (object item in collectionArgs.OldItems)
{
(item as INotifyPropertyChanged).PropertyChanged -= this.OnItemPropertyChanged;
}
}
if (collectionArgs.NewItems != null)
{
foreach (object item in collectionArgs.NewItems)
{
(item as INotifyPropertyChanged).PropertyChanged += this.OnItemPropertyChanged;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment