0

My class has a public List field. I want to detect when someone changes this collection. However, writing my own Add/Remove wrapper around this collection seems wasteful. Is there a way to get notifications about changes in collection with delegates or something like that?

Max Yankov
  • 12,551
  • 12
  • 67
  • 135

3 Answers3

3

Use ObservableCollection<T> instead you may find reference here.

David
  • 15,894
  • 22
  • 55
  • 66
0

There already exists a collection you've described and it's called ObservableCollection.

It has CollectionChanged event, so just subscribe your event handler there and i'll get called every time item is added or removed from collection..

MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
0

Use BindingList<T> instead. It offers a ListChanged event. It is also accepted as DataSource in many controls such as a Listbox or a Grid.

As mentioned in this answer the BindingList offers a lot more than ObservableCollection

If you want to change a list in a listbox and changes to that list be reflected to the UI, you can set a BindingList<> as datasource to the Listbox and then simply manipulate the list. The Listbox will handle the ListChanged event and will display changes without having to manually do it by your self.

If you are going to use it in Winforms you should go with BindingList and if you are going to use it on a WPF app then go with ObservableCollection.

Community
  • 1
  • 1
Odys
  • 8,951
  • 10
  • 69
  • 111