How to handle add to list event?

Tomasz Smykowski picture Tomasz Smykowski · Aug 19, 2009 · Viewed 68.8k times · Source

I have a list like this:

List<Controls> list = new List<Controls>

How to handle adding new position to this list?

When I do:

myObject.myList.Add(new Control());

I would like to do something like this in my object:

myList.AddingEvent += HandleAddingEvent

And then in my HandleAddingEvent delegate handling adding position to this list. How should I handle adding new position event? How can I make this event available?

Answer

MattH picture MattH · Aug 19, 2009

I believe What you're looking for is already part of the API in the ObservableCollection(T) class. Example:

ObservableCollection<int> myList = new ObservableCollection<int>();

myList.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(
    delegate(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)                    
    {
        if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
        {
            MessageBox.Show("Added value");
        }
    }
);

myList.Add(1);