Monitoring Changes of Individual Objects Inside ObservableCollection

I needed to monitor individual objects of a collection in order to make a function available only when one of them did not match its initial state. Here’s how I decided to do it.

The ObservableCollection only fires its event when the collection changes. If the collection doesn’t change, but one of the objects in it does change its state, the event is not fired, and bindings are not updated. Let’s look at how this problem could be solved.

....
    collection.CollectionChanged += (s, e) => {
        if (e.OldItems != null)
            foreach(var item in e.OldItems) {
                var inpc = item as INotifyPropertyChanged;
                inpc?.PropertyChanged -= inpc_PropertyChanged;
            }
        if (e.NewItems != null)
        foreach(var item in e.NewItems) {
            var inpc = item as INotifyPropertyChanged;
            inpc?.PropertyChanged += inpc_PropertyChanged;
        }
    };
....

private void inpc_PropertyChanged(object sender, PropertyChangedEventArgs e) {
    if (e.PropertyName == "DesiredPropertyName")
        Handle();
}

The object which is the focus of the collection should implement INotifyPropertyChanged, but if I included the null check in there anyways. Anytime items are included or removed from the collection, you have to add or remove the handler so items that leave the collection are no longer monitored, and items entering the collection are. For this reason, I defined the method instead of just using a lambda expression, or anonymous function.

One other thing that may trip you up is that you may want to monitor the collection, and reset variables if the collection is empty. This could come in handy if you are monitoring how many objects have changed. If you do not reset the counter back to zero when the collection is refreshed to reflect all objects are unchanged, you will not get expected results.

Author: Peter

Thank you for visiting my profile. I encourage you to get in contact with me, and follow me on GitHub : https://github.com/emancipatedMind. I look forward to collaborating with you.

Leave a Reply

Your email address will not be published. Required fields are marked *