Click here to Skip to main content
11,574,503 members (56,312 online)
Click here to Skip to main content

How to Listen to Property Changes of Items of an ObservableCollection

, 13 Dec 2013 CPOL 26.6K 18
Rate this:
Please Sign up or sign in to vote.
How to listen to property changes of items in an ObservableCollection.

Introduction

This tip describes how to make use of ObservableCollection to reflect changes occurring in the properties of its items.

Background

ObservableCollection is a part of the life of the WPF community. Most of us are aware that this collection listens to changes occurring in the collection, like an item being added or removed from it.

However, many beginners stumble when they are required to listen to changes occurring in the items of the ObservableCollection. It comes to them as a surprise that their changes do not reflect even after they implement the most famous INotifyPropertyChanged interface on their classes.

Community has solved this issue already. However, I feel that the solution is scattered in bits and pieces. So, here I have tried to put it in a structured way.

Using the Code

Create a class with the given code and make sure you are referring to this namespace. Or you may like to modify the namespace as per your naming conventions.

I call this class ItemsChangeObservableCollection.

It is inherited from ObservableCollection. So the usage of this class is just like ObservableCollection, however, it only allows classes that implement the INotifyPropertyChanged interface.

This class is simple but powerful. It simply registers to the PropertyChanged event of the item and calls OnCollectionChanged of the ObservableCollection when the item raises the PropertyChanged event.

As usual, one should be very careful about the memory leaks when there are event subscriptions involved. So, make sure to call the Clear() method once you are done with your collection allowing GC to collect it.

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

namespace VJCollections
{
    /// <summary>
    ///     This class adds the ability to refresh the list when any property of
    ///     the objects changes in the list which implements the INotifyPropertyChanged. 
    /// </summary>
    /// <typeparam name="T">
    public class ItemsChangeObservableCollection<T> : 
           ObservableCollection<T> where T : INotifyPropertyChanged
    {
        protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == NotifyCollectionChangedAction.Add)
            {
                RegisterPropertyChanged(e.NewItems);
            }
            else if (e.Action == NotifyCollectionChangedAction.Remove)
            {
                UnRegisterPropertyChanged(e.OldItems);
            }
            else if (e.Action == NotifyCollectionChangedAction.Replace)
            {
                UnRegisterPropertyChanged(e.OldItems);
                RegisterPropertyChanged(e.NewItems);
            }
            
            base.OnCollectionChanged(e);
        }

        protected override void ClearItems()
        {
            UnRegisterPropertyChanged(this);
            base.ClearItems();
        }

        private void RegisterPropertyChanged(IList items)
        {
            foreach (INotifyPropertyChanged item in items)
            {
                if (item != null)
                {
                    item.PropertyChanged += new PropertyChangedEventHandler(item_PropertyChanged);
                }
            }
        }

        private void UnRegisterPropertyChanged(IList items)
        {
            foreach (INotifyPropertyChanged item in items)
            {
                if (item != null)
                {
                    item.PropertyChanged -= new PropertyChangedEventHandler(item_PropertyChanged);
                }
            }
        }

        private void item_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            base.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
        }
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Vijaya Krishna Paruchuri
Software Developer (Senior)
India India
No Biography provided

You may also be interested in...

Comments and Discussions

 
QuestionPlease reply as early as possible ( Vijaya Krishna Paruchuri). Pin
Ujjval116-Jun-14 3:43
groupUjjval116-Jun-14 3:43 
Questionitem_PropertyChanged event is not being called when property is changed. Pin
Ujjval116-Jun-14 2:37
groupUjjval116-Jun-14 2:37 
QuestionYes, you are right! Pin
Dmitri Raiko10-Dec-13 23:22
memberDmitri Raiko10-Dec-13 23:22 
AnswerRe: Yes, you are right! Pin
Vijaya Krishna Paruchuri11-Dec-13 3:05
memberVijaya Krishna Paruchuri11-Dec-13 3:05 
QuestionMemory leaks Pin
Dmitri Raiko10-Dec-13 21:35
memberDmitri Raiko10-Dec-13 21:35 
AnswerRe: Memory leaks Pin
Vijaya Krishna Paruchuri10-Dec-13 22:38
memberVijaya Krishna Paruchuri10-Dec-13 22:38 
QuestionBindingList<T> Pin
giantism5410-Dec-13 9:08
membergiantism5410-Dec-13 9:08 
AnswerRe: BindingList<T> Pin
Vijaya Krishna Paruchuri11-Dec-13 3:04
memberVijaya Krishna Paruchuri11-Dec-13 3:04 
GeneralRe: BindingList<T>0 Pin
laythe1232-Jan-14 3:17
memberlaythe1232-Jan-14 3:17 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150624.2 | Last Updated 13 Dec 2013
Article Copyright 2013 by Vijaya Krishna Paruchuri
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid