There is a class MyClass , in which there is an event on a property change (for example, through INotifyPropertyChanged ). In another class MyMainClass , a list of such objects is created public List<MyClass> Data { get; set; } public List<MyClass> Data { get; set; } public List<MyClass> Data { get; set; } . How to handle an event when the value of a property has changed in the list of objects? Added / deleted item in / list is not interested.

  • need to respond to a change in the property of a particular object? - rdorn

2 answers 2

To do this, you will have to implement your own collection, which will keep track of the added and removed items. If you need an item delete / add event, follow this class from the ObservableCollection<T> .

 // Не является потокобезопасной public sealed class ItemObservableCollection<T> : Collection<T> where T : INotifyPropertyChanged { public event PropertyChangedEventHandler ItemPropertyChanged; protected override void InsertItem(int index, T item) { base.InsertItem(index, item); item.PropertyChanged += item_PropertyChanged; } protected override void RemoveItem(int index) { var item = this[index]; base.RemoveItem(index); item.PropertyChanged -= item_PropertyChanged; } protected override void SetItem(int index, T item) { var oldItem = this[index]; base.SetItem(index, item); oldItem.PropertyChanged -= item_PropertyChanged; item.PropertyChanged += item_PropertyChanged; } protected override void ClearItems() { foreach (var item in Items) { item.PropertyChanged -= item_PropertyChanged; } base.ClearItems(); } private void item_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (ItemPropertyChanged != null) { ItemPropertyChanged(sender, e); } } } 
  • It seems you can use BindingList : ru.stackoverflow.com/a/477539 - VladD
  • @VladD I already forgot about such a thing :). True, working with it is a little more clumsy - there is a general event for changing the elements and changing the collection. - andreycha
  • I have never used this container at all: in WPF everything works fine without it, ObservableCollection<T> enough. - VladD

As far as I understand, BindingList<T> will suit you instead of List<T> : it can send notifications not only about changing the list, but also about changing list elements .

 var l = new BindingList<MyClass>(); l.RaiseListChangedEvents = true; // кажется, нужно ещё ((IRaiseItemChangedEvents)l).RaisesItemChangedEvents = true; l.ListChanged += (o, args) => { if (args.ListChangedType == ListChangedType.ItemChanged) // изменился элемент с индексом e.NewIndex };