Observe Collection changed - CSharp System.Collections.ObjectModel

CSharp examples for System.Collections.ObjectModel:ObservableCollection

Description

Observe Collection changed

Demo Code


using System.Collections.Specialized;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Linq;
using System;/*from  w w  w .j  a  v a  2s . c om*/

public class Main{
    public static void ObserveCollection<T>(this ObservableCollection<T> collection, Action<T> addAction, Action<T> removeAction)
      {
         collection.CollectionChanged += (sender, args) =>
         {
            if (args.Action == NotifyCollectionChangedAction.Add)
            {
               foreach (var newItem in args.NewItems)
               {
                  if (addAction != null)
                     addAction((T)newItem);
               }
            }
            else if (args.Action == NotifyCollectionChangedAction.Remove)
            {
               foreach (var removeItem in args.OldItems)
               {
                  if (removeAction != null)
                     removeAction((T)removeItem);
               }
            }
         };
      }
}

Related Tutorials