I was looking around in ObservableCollection<T> using a decompiler and saw some curious OnPropertyChanged code that I’d never seen before.
public class ObservableCollection<T> : Collection<T>, INotifyCollectionChanged, INotifyPropertyChanged
{
private const string IndexerName = "Item[]";
protected override void ClearItems()
{
...
base.OnPropertyChanged("Count");
base.OnPropertyChanged("Item[]");
...
}
}
What does the OnPropertyChanged("Item[]") call do and how would that be helpful when writing my own code?
It must be doing something different than a standard OnPropertyChanged call since ‘Item’ is not a property on the object and ‘[]‘ surely isn’t part of ‘any’ property name.
The call to
OnPropertyChanged("Item[]")is required to follow the spirit ofINotifyPropertyChanged. The data returned by the default indexerItemhas changed.In your specific example, the collection has been cleared, so if you are indexing into a specific item the collection, then you need to be notified that the object reference you are interested in may be different.
Edit
After Kevin’s comment about binding to an indexer, I wrote an app to test the binding.
I created an
ObservableCollection<int>and populated like this:If you bind to something via the indexer like this, it will display
3:And then change the object at that index at runtime,
The
TextBlockwill update and display the new value10.