22
public ObservableCollection<IndividualEntityCsidClidDetail> IncludedMembers { get; set; }

Let say I have a reference to IncludedMembers I want an event to occur when collection items are added/removed/edited.

miguel
  • 2,961
  • 4
  • 26
  • 34
SOF User
  • 7,590
  • 22
  • 75
  • 121
  • Are you using the collection in a WPF or WinForms environment? What are you trying to achieve? Binding might be better than event handling if you are in WPF. – miguel May 15 '11 at 10:32

3 Answers3

44

handle the CollectionChanged event

//register the event so that every time when there is a change in collection CollectionChangedMethod method will be called

    yourCollection.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler 
(CollectionChangedMethod);

Create a method like this

private void CollectionChangedMethod(object sender, NotifyCollectionChangedEventArgs e)
{
       //different kind of changes that may have occurred in collection
       if(e.Action == NotifyCollectionChangedAction.Add)
        {
            //your code
        }
        if (e.Action == NotifyCollectionChangedAction.Replace)
        {
            //your code
        }
        if (e.Action == NotifyCollectionChangedAction.Remove)
        {
            //your code
        }
        if (e.Action == NotifyCollectionChangedAction.Move)
        {
            //your code
        }
}
Haris Hasan
  • 29,856
  • 10
  • 92
  • 122
5

Just register to the collection's CollectionChanged event. It will raise events when you add or remove items or otherwise, change the contents of the collection.

If you want to receive events when properties of the items in the collection change, you'd need to make sure that the items are IObservable first then Subscribe() to the individual objects.

Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272
-3

That is what observable collections are for.

Simply bind to the collection and you are sorted!

miguel
  • 2,961
  • 4
  • 26
  • 34
  • 3
    The OP asked how to listen to changes in the collection. He didn't discuss binding... – Gabe Aug 23 '15 at 10:55