Home >Backend Development >C++ >Does a Collection Exist That Monitors Changes in Both Itself and Its Elements?
This article explores the concept of monitoring collections themselves and changes to collection elements. Typically, ObservableCollection
notifies changes to the collection itself, but not changes to its elements.
Is there an existing collection that can monitor element changes?
Yes, you can create a custom implementation extending ObservableCollection
to meet this requirement.
Custom ObservableCollection with element monitoring capabilities:
This is a modified ObservableCollection
version:
<code class="language-csharp">public class ObservableCollectionEx<T> : ObservableCollection<T> where T : INotifyPropertyChanged { // 订阅添加到项目中的 PropertyChanged 事件 protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e) { Subscribe(e.NewItems); base.OnCollectionChanged(e); } // 取消订阅从移除的项目中移除的 PropertyChanged 事件,并在清除集合时清除所有项目 protected override void ClearItems() { foreach (T element in this) element.PropertyChanged -= ContainedElementChanged; base.ClearItems(); } // 订阅元素中的 PropertyChanged 事件 private void Subscribe(IList iList) { if (iList != null) { foreach (T element in iList) element.PropertyChanged += ContainedElementChanged; } } // 取消订阅元素中的 PropertyChanged 事件 private void Unsubscribe(IList iList) { if (iList != null) { foreach (T element in iList) element.PropertyChanged -= ContainedElementChanged; } } // 当包含的元素属性更改时发出通知 private void ContainedElementChanged(object sender, PropertyChangedEventArgs e) { OnPropertyChanged(e); } }</code>
Use this custom collection:
<code class="language-csharp">ObservableCollectionEx<Element> collection = new ObservableCollectionEx<Element>(); ((INotifyPropertyChanged)collection).PropertyChanged += (x, y) => ReactToChange();</code>
Notes when using the PropertyChanged event:
Note that when using the PropertyChanged
event on a custom collection, the sender will be the collection itself, not the element that changed. If necessary, you can define separate ContainerElementChanged
events for more explicit notifications.
The above is the detailed content of Does a Collection Exist That Monitors Changes in Both Itself and Its Elements?. For more information, please follow other related articles on the PHP Chinese website!