How to get changes in ObservableCollection

SOF User picture SOF User · May 15, 2011 · Viewed 18.9k times · Source
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.

Answer

Haris Hasan picture Haris Hasan · May 15, 2011

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
        }
}