WPF: Binding List to ListBox in wpf?

Total Post:24

Points:168
WPF 
WPF
 2686  View(s)
Ratings:
Rate this:

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?

  1. Post:412

    Points:2888
    Re: WPF: Binding List to ListBox in wpf?

    I think that the problem is that, although you are notifying the binding framework that the property has changed, the actual value of the property remains the same. That is to say that although the listbox may reevaluate the value of its ItemsSource binding, it will find that it is still the same object instance as previously. For example, imagine that the listbox reacts by to the property changed event somehow similar to the below.

    private void OnItemsSourceBindingChanged()
    {
        var newValue = this.EvaluateItemsSourceBinding();
        if (newValue != this.ItemsSource) //it will be equal, as its still the same list
        {
            this.AddNewItems();
        }
    }

    In your example, this would mean that it would not reevaluate the items.

      Modified On Mar-30-2018 06:31:10 AM

Answer