WPF: Binding List to ListBox
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.
Related videos on Youtube
Damian
Updated on May 31, 2022Comments
-
Damian almost 2 years
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?
-
Thomas Levesque almost 13 yearsPlease post your real code... The code you posted can't work, even with an ObservableCollection. And the NotifyPropertyChanged changes nothing, since you're not using it
-
-
Damian almost 13 yearsThanks, it is public, I forgot to write it in the code. Now the code is changed
-
Damian almost 13 yearsThanks, it is public, I forgot to write it in the code. Now the code is changed
-
ebhh2001 over 7 yearsThanks explaining why
ObservableCollection
is useful in data binding.