ObservableCollection
implements INotifyPropertyChanged
. This interface exposes events that allow consumers of your collection to be notified when the contents of the collection change.
This is mainly used when binding in WPF, for example let’s say we have an ObservableCollection<string>
:
ObservableCollection<string> MyStrings
{
get
{
// return a collection with some strings here
}
}
and this control in XAML:
<ComboBox ItemsSource="{Binding MyStrings}" />
The ComboBox
will show the strings inside your ObservableCollection
. So far, this would have worked just fine with a List<string>
as well. However, if you now add some strings to the collection, for example:
<Button Click="AddSomeStrings" Content="Click me!" />
private void AddSomeStrings(object sender, RoutedEventArgs e)
{
this.MyStrings.Add("Additional string!");
}
you will see that the contents of the ComboBox
will be immediately updated and the string will be added to the list of options. This is all accomplished using INotifyCollectionChanged
.
solved regarding ObservableCollection in c#