In .NET 4.0, there isn't a single property defined by ObservableCollection<T>
nor does it override any property of its parent or interfaces. So why does ObservableCollection<T>
implement INotifyPropertyChanged
?
One reason I can think of is that it makes it easier for subclasses to define their own properties and use the OnPropertyChanged
method implemented by ObservableCollection<T>
. But is this the main reason?
Both Count
and Item[]
changes are notified. Here's a sample (using C# 6 just for the string interpolation):
using System;
using System.ComponentModel;
using System.Collections.ObjectModel;
class Test
{
static void Main(string[] args)
{
var collection = new ObservableCollection<string>();
((INotifyPropertyChanged)collection).PropertyChanged += (sender, e) =>
{
Console.WriteLine($" {e.PropertyName} changed");
};
Console.WriteLine("Adding");
collection.Add("Item");
Console.WriteLine("Adding");
collection.Add("Other item");
Console.WriteLine("Removing");
collection.RemoveAt(0);
Console.WriteLine("Changing");
collection[0] = "Different";
}
}
Output:
Adding
Count changed
Item[] changed
Adding
Count changed
Item[] changed
Removing
Count changed
Item[] changed
Changing
Item[] changed
See more on this question at Stackoverflow