Click here to Skip to main content
15,885,278 members
Articles / Programming Languages / C#
Tip/Trick

How to Listen to Property Changes of Items of an ObservableCollection

Rate me:
Please Sign up or sign in to vote.
4.42/5 (9 votes)
13 Dec 2013CPOL1 min read 121.9K   27   13
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.

C#
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)


Written By
Software Developer (Senior)
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionExample and use in VB.Net? Pin
Tim8w28-Aug-18 12:42
Tim8w28-Aug-18 12:42 
QuestionExample! Pin
Al3xI98O21-Apr-16 2:53
Al3xI98O21-Apr-16 2:53 
AnswerRe: Example! Pin
Eyüp Erdoğan7-Nov-17 3:54
Eyüp Erdoğan7-Nov-17 3:54 
PraiseHow to Listen to Property Changes of Items of an ObservableCollection Pin
Member 112730651-Apr-16 11:53
Member 112730651-Apr-16 11:53 
QuestionPlease reply as early as possible ( Vijaya Krishna Paruchuri). Pin
Ujjval116-Jun-14 3:43
Ujjval116-Jun-14 3:43 
Questionitem_PropertyChanged event is not being called when property is changed. Pin
Ujjval116-Jun-14 2:37
Ujjval116-Jun-14 2:37 
QuestionYes, you are right! Pin
Dmitri Raiko10-Dec-13 23:22
Dmitri Raiko10-Dec-13 23:22 
AnswerRe: Yes, you are right! Pin
Vijaya Krishna Paruchuri11-Dec-13 3:05
Vijaya Krishna Paruchuri11-Dec-13 3:05 
QuestionMemory leaks Pin
Dmitri Raiko10-Dec-13 21:35
Dmitri Raiko10-Dec-13 21:35 
AnswerRe: Memory leaks Pin
Vijaya Krishna Paruchuri10-Dec-13 22:38
Vijaya Krishna Paruchuri10-Dec-13 22:38 
QuestionBindingList<T> Pin
giantism5410-Dec-13 9:08
giantism5410-Dec-13 9:08 
AnswerRe: BindingList<T> Pin
Vijaya Krishna Paruchuri11-Dec-13 3:04
Vijaya Krishna Paruchuri11-Dec-13 3:04 
GeneralRe: BindingList<T>0 Pin
laythe1232-Jan-14 3:17
laythe1232-Jan-14 3:17 

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

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