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?
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);
You could inherit from List and add your own handler, something like
using System; using System.Collections.Generic; namespace test { class Program { class MyList<T> : List<T> { public event EventHandler OnAdd; public new void Add(T item) // "new" to avoid compiler-warnings, because we're hiding a method from base-class { if (null != OnAdd) { OnAdd(this, null); } base.Add(item); } } static void Main(string[] args) { MyList<int> l = new MyList<int>(); l.OnAdd += new EventHandler(l_OnAdd); l.Add(1); } static void l_OnAdd(object sender, EventArgs e) { Console.WriteLine("Element added..."); } } }
Be aware that you have to re-implement all methods which add objects to your list. AddRange()
will not fire this event, in this implementation.
We did not overload the method. We hid the original one. If you Add()
an object while this class is boxed in List<T>
, the event will not be fired!
MyList<int> l = new MyList<int>(); l.OnAdd += new EventHandler(l_OnAdd); l.Add(1); // Will work List<int> baseList = l; baseList.Add(2); // Will NOT work!!!
What you need is a class that has events for any type of modification that occurs in the collection. The best class for this is BindingList<T>
. It has events for every type of mutation which you can then use to modify your event list.
You can't do this with List<T>
. However, you can do it with ObservableCollection<T>
. See ObservableCollection<T>
Class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With