WPF: Binding List to ListBox

Damian picture Damian · May 19, 2011 · Viewed 18.8k times · Source

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?

Answer

Thomas Levesque picture Thomas Levesque · May 19, 2011

Your property has to be public, or the binding engine won't be able to access it.


EDIT:

After changing list to ObservableCollection and removing the NotifyPropertyChanged handler everything works.

That's precisely why the ObservableCollection<T> class was introduced... ObservableCollection<T> implements INotifyCollectionChanged, 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 PropertyChanged event does refresh the binding, but then it realizes that it's the same instance of List<T> as before, so it reuses the same ICollectionView as the ItemsSource, and the content of the ListBox isn't refreshed.