11

I have a class which contains a list :

public class a
{
    private List<MyType> _Children;

    public Children
    {
        get { return(_Children); }
        set { _Children = value ; }
    }
}

I want to create an event and fire it whenever my list (_Children here) is changed for example an item is added to it or removed from it or it's cleared.

thanks

Asef Hossini
  • 655
  • 8
  • 11
Asha
  • 3,871
  • 7
  • 44
  • 57

3 Answers3

20

Change your list to an ObservableCollection<T>. It implements INotifyCollectionChanged, so you can subscribe to change events on it.

Another option is to use BindingList<T>, if you need full list semantics.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • 9
    One thing to remember about ObservableCollection is it will throw an exception if you try to add an element to it from thread other than the one you created it on (whether or not you lock on it). – Sam Harwell Oct 22 '09 at 14:29
3

See ObservableCollection

Henrik
  • 23,186
  • 6
  • 42
  • 92
0

Or if you want to control the Add and remove methods and raise event, check Collection<T> out.

http://msdn.microsoft.com/en-us/library/ms132397.aspx

m3kh
  • 7,881
  • 2
  • 31
  • 37