问题描述
我有一个类:
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));
}
}
}
和有约束力的(用户控件的DataContext的是A的一个实例):
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
改变列表的ObservableCollection和去除NotifyPropertyChanged处理后的一切工作。
After changing list to ObservableCollection and removing the NotifyPropertyChanged handler everything works.
为什么这个列表不工作?
Why the list is not working?
推荐答案
编辑:
改变列表的ObservableCollection和去除NotifyPropertyChanged处理后的一切工作。
这是precisely为什么的ObservableCollection&LT; T&GT;引入
类... 的ObservableCollection&LT; T&GT;
工具 INotifyCollectionChanged
,这使得当一个项目被添加/删除/替换它来通知用户界面。 列表&LT; T&GT;
不会触发任何通知,所以当列表的内容改变了UI无法检测
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.
这是你提出的的PropertyChanged
事件不刷新绑定,但随后意识到它的名单,LT的同一个实例的事实; T&GT;
和以前一样,所以重复使用相同的的ICollectionView
为一体的的的ItemsSource
,内容的ListBox
没有刷新。
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.
这篇关于WPF:绑定列表到列表框控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!