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.

1
  • 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, 2011 at 10:32

3 Answers 3

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
        }
}
3
  • 1
    this doesn't with simply changes of the fieds of objects in includeMembers Sep 23, 2014 at 6:49
  • to simplify changes in the members , use notify property changed in the members class Aug 12, 2015 at 19:11
  • What about NotifyCollectionChangedAction.Reset? Does it also call NotifyCollectionChangedAction.Remove?
    – Deantwo
    Sep 7, 2017 at 8:18
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.

-4

That is what observable collections are for.

Simply bind to the collection and you are sorted!

1
  • 4
    The OP asked how to listen to changes in the collection. He didn't discuss binding...
    – Gabe
    Aug 23, 2015 at 10:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.