moorara
moorara

Reputation: 4226

How to add changing event to List<T> class in C#?

I want to add an event to the List generic class in C# in order to handle changing items of list in case that a new item is added or removed. I create class and inherit it from List class. Since the Add, Insert, and Remove methods of this class can't be overrode, I define new Add, Insert, and Remove methods by new keyword and call the parent methods and then raise my event. I used this class as a property in an User Control. In design mode when I change the collection with provided GUI in .net development studio, the event does not work. How can I solve this problem?

Here is an example of defining such a class

public class SelectorItemCollection : List<SelectorItem>
{
    public new void Add(SelectorItem Item)
    {

        //Call parent method
        base.Add(Item);

        //Raise changing event
        this.OnCollectionChanged();

    }
}

I defined a property in my user control class like this:

    [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
    public SelectorItemCollection Items { get; }

My desired state that when I change the items in this dialog, I want to raise a changing event from collection class.

enter image description here

Upvotes: 1

Views: 7859

Answers (3)

Thomas Levesque
Thomas Levesque

Reputation: 292535

Don't reinvent the wheel, use a collection class that already supports such notifications, like ObservableCollection<T> or BindingList<T> (if you're using data binding in WPF, use the former; in Windows Forms, use the latter).

If you want to implement your own, don't inherit from List<T>, because it was not designed for inheritance. Instead, you could use Collection<T> as your base class.

Upvotes: 14

JDunkerley
JDunkerley

Reputation: 12505

You could use a System.ComponentModel.BindingList<SelectorItem> which has various events on it.

Upvotes: 1

Sebastian Piu
Sebastian Piu

Reputation: 8008

Have at look at BindingList<T> instead, which seems to be what you are trying to replicate

Upvotes: 2

Related Questions