base.OnPropertyChanged(“Item []”)在ObservableCollection中做了什么?

时间:2012-08-08 19:24:47

标签: .net wpf observablecollection inotifypropertychanged

我使用反编译器在ObservableCollection<T>中环顾四周,看到了一些我以前从未见过的好奇的OnPropertyChanged代码。

public class ObservableCollection<T> : Collection<T>, INotifyCollectionChanged, INotifyPropertyChanged
{    
    private const string IndexerName = "Item[]";

    protected override void ClearItems()
    {
        ...
        base.OnPropertyChanged("Count");
        base.OnPropertyChanged("Item[]");
        ...
    }
}

OnPropertyChanged("Item[]")调用做了什么以及在编写自己的代码时如何有用?

必须执行与标准OnPropertyChanged调用不同的操作,因为'Item'不是对象的属性,'[]'肯定不属于'any'属性名称。< / p>

1 个答案:

答案 0 :(得分:2)

要求OnPropertyChanged("Item[]")致电INotifyPropertyChanged的精神。默认索引器Item返回的数据已更改。

在您的特定示例中,集合已被清除,因此如果您要将集合索引到特定项目,则需要通知您感兴趣的对象引用可能不同。

修改

在Kevin关于绑定到索引器的评论之后,我写了一个应用来测试绑定。

我创建了一个ObservableCollection<int>并填充如下:

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

如果您通过这样的索引器绑定某些内容,它将显示3

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

然后在运行时更改该索引处的对象,

this.Indexed.Insert(2, 10);

TextBlock将更新并显示新值10