Though the answer of @rshepp is a perfect point, it is not the whole story.
The ObservableCollection
class is designed to enable feedback when items are added or removed from the collection. But if one of the items inside collection changes a value, your collection will not notice - unless the contained items implement the INotifyPropertyChanged interface and you attach to the event handler.
public class MotherClass
{
public MotherClass()
{
MonitoredItems = new();
MonitoredItems.CollectionChanged += MonitoredItems_CollectionChanged;
}
public ObservableCollection<Item> MonitoredItems { get; }
private void MonitoredItems_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.OldItems is not null)
{
foreach (Item item in e.OldItems)
{
//Removed items
item.PropertyChanged -= MonitoredItem_PropertyChanged;
}
}
else if (e.NewItems is not null)
{
foreach (Item item in e.NewItems)
{
//Added items
item.PropertyChanged += MonitoredItem_PropertyChanged;
}
}
}
private void MonitoredItem_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (sender is not Item sendingItem)
return;
Trace.WriteLine($"The {nameof(Item)} object with Name {sendingItem.Name} has a change in its property {e.PropertyName} ");
}
}
Of course, you are free to extend this example MotherClass to MotherClass extending ObservableCollection, if you are able to contain the the sub-property changed event inside the collection.
Note there is no setter for the ObservableCollection to keep the attached event handler intact. The outside code can still use something like .Clear
or .ReplaceRange
to set brand new collection values.