I have a class:
public class A : INotifyPropertyChanged
{
public List<B> bList { get; set; }
public void AddB(B b)
{
bList.Add(b);
NotifyPropertyChanged("bList");
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
}
And a binding (DataContext of UserControl is an instance of A):
<ListBox ItemsSource="{Binding Path=bList}" />
Elements are shown, the ListBox is not updated after new object is added to List
After changing list to ObservableCollection and removing the NotifyPropertyChanged handler everything works.
Why the list is not working?
Your property has to bepublic, or the binding engine won’t be able to access it.EDIT:
That’s precisely why the
ObservableCollection<T>class was introduced…ObservableCollection<T>implementsINotifyCollectionChanged, which allows it to notify the UI when an item is added/removed/replaced.List<T>doesn’t trigger any notification, so the UI can’t detect when the content of the list has changed.The fact that you raise the
PropertyChangedevent does refresh the binding, but then it realizes that it’s the same instance ofList<T>as before, so it reuses the sameICollectionViewas theItemsSource, and the content of theListBoxisn’t refreshed.