ObservableCollectionExtension.cs

58 lines | 2.153 kB Blame History Raw Download
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;

namespace WPF.Common.WPF
{

    public static class ObservableCollectionExtension
    {
        public static void NotifyPropertyChanged<T>(this ObservableCollection<T> observableCollection, Action<T, PropertyChangedEventArgs> callBackAction)
            where T : INotifyPropertyChanged
        {
            observableCollection.CollectionChanged += (sender, args) =>
            {
                //Does not prevent garbage collection says: http://stackoverflow.com/questions/298261/do-event-handlers-stop-garbage-collection-from-occuring
                //publisher.SomeEvent += target.SomeHandler;
                //then "publisher" will keep "target" alive, but "target" will not keep "publisher" alive.

                //if (args.NewItems == null)
                //    return;
                //foreach (T item in args.NewItems)
                //{
                //    item.PropertyChanged += (obj, eventArgs) =>
                //    {
                //        callBackAction((T)obj, eventArgs);
                //    };
                //}

                if (args.OldItems != null)
                    foreach (T item in args.OldItems)
                        if (item != null && item is INotifyPropertyChanged i)
                            i.PropertyChanged -= (obj, eventArgs) =>
                            {
                                callBackAction((T)obj, eventArgs);
                            };


                if (args.NewItems != null)
                    foreach (T item in args.NewItems)
                        if (item != null && item is INotifyPropertyChanged i)
                        {
                            i.PropertyChanged -= (obj, eventArgs) =>
                            {
                                callBackAction((T)obj, eventArgs);
                            };

                            i.PropertyChanged += (obj, eventArgs) =>
                            {
                                callBackAction((T)obj, eventArgs);
                            };
                        };

            };
        }
    }
}