Home >Backend Development >C++ >Does an ObservableCollection Exist That Tracks Both Collection and Element Property Changes?
ObservableCollection that monitors collection and element attribute changes
Question:
Is there a collection that can simultaneously monitor changes in the collection itself and changes in the attributes of its elements?
Solution:
If no ready-made collection meets this requirement, you can create an implementation that extends ObservableCollection
to monitor its elements for PropertyChanged
events.
Implementation:
The following is an example implementation of ObservableCollectionEx
that implements this functionality:
<code class="language-csharp">public class ObservableCollectionEx<T> : ObservableCollection<T> where T : INotifyPropertyChanged { protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e) { Unsubscribe(e.OldItems); Subscribe(e.NewItems); base.OnCollectionChanged(e); } protected override void ClearItems() { foreach (T element in this) element.PropertyChanged -= ContainedElementChanged; base.ClearItems(); } private void Subscribe(IList iList) { if (iList != null) { foreach (T element in iList) element.PropertyChanged += ContainedElementChanged; } } private void Unsubscribe(IList iList) { if (iList != null) { foreach (T element in iList) element.PropertyChanged -= ContainedElementChanged; } } private void ContainedElementChanged(object sender, PropertyChangedEventArgs e) { OnPropertyChanged(new PropertyChangedEventArgs(e.PropertyName)); //Corrected this line. } }</code>
Usage:
Use ObservableCollection
like a normal ObservableCollectionEx
, but convert it to a INotifyPropertyChanged
to subscribe to its element's property change events:
<code class="language-csharp">ObservableCollectionEx<Element> collection = new ObservableCollectionEx<Element>(); ((INotifyPropertyChanged)collection).PropertyChanged += (x, y) => ReactToChange();</code>
Note: In the ContainedElementChanged
method, the parameter of OnPropertyChanged
needs to be a new PropertyChangedEventArgs
instance instead of using e
directly. This has been corrected in the code above. This ensures that the correct property name is passed to the event handler.
The above is the detailed content of Does an ObservableCollection Exist That Tracks Both Collection and Element Property Changes?. For more information, please follow other related articles on the PHP Chinese website!