Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does base.OnPropertyChanged("Item[]") do inside ObservableCollection?

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.

like image 224
Kevin Kalitowski Avatar asked Aug 05 '26 17:08

Kevin Kalitowski


1 Answers

The call to OnPropertyChanged("Item[]") is required to follow the spirit of INotifyPropertyChanged. The data returned by the default indexer Item has 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:

this.Indexed.Add(1);
this.Indexed.Add(2);
this.Indexed.Add(3);

If you bind to something via the indexer like this, it will display 3:

<TextBlock Text="{Binding Indexed[2]}" />

And then change the object at that index at runtime,

this.Indexed.Insert(2, 10);

The TextBlock will update and display the new value 10.

like image 84
davisoa Avatar answered Aug 08 '26 12:08

davisoa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!