Home > DeveloperSection > Forums > WPF: Binding List to ListBox in wpf?
Dag Hammarskjold
Dag Hammarskjold

Total Post:24

Points:168
Posted on    August-10-2013 5:14 AM

 WPF WPF 
Ratings:


 1 Reply(s)
 1516  View(s)
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?



Pravesh Singh

Total Post:411

Points:2881
Posted on    August-10-2013 5:25 AM

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.


Don't want to miss updates? Please click the below button!

Follow MindStick