3

I write a control that displays a list of items (in this case just strings). I gave the developer a list of items where he can add and remove items (see code below). I wished there would be a way to be notified when a new item has been added and stuff. So as a reaction the control can update.

private List<string> items = new List<string>();

public List<string> Items
{ get { return items; } }

How can I do that ? List<...> has no events. What can I do ?

Bitterblue
  • 13,162
  • 17
  • 86
  • 124

2 Answers2

9

Have a look at BindingList<T> and ObservableCollection<T>. This answer explains the difference between the two.

Apart from binding, you can subscribe to the change events like so:

BindingList<T>.ListChanged:

items.ListChanged += (sender, e) => {
    // handle the change notification
};

ObservableCollection<T>.CollectionChanged:

items.CollectionChanged += (sender, e) => {
    // handle the change notification
};
Community
  • 1
  • 1
canon
  • 40,609
  • 10
  • 73
  • 97
7

Use ObservableCollection<string> instead of a List. That class comes with built-in support for change notification events.

Jon
  • 428,835
  • 81
  • 738
  • 806