我有一堂课:
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));
}
}
}
和一个绑定(UserControl 的 DataContext 是 A 的实例):
<ListBox ItemsSource="{Binding Path=bList}" />
显示元素,将新对象添加到列表后列表框不会更新
将列表更改为 ObservableCollection 并删除 NotifyPropertyChanged 处理程序后,一切正常。
为什么该列表不起作用?
您的财产必须是public
,否则绑定引擎将无法访问它。
EDIT:
将列表更改为 ObservableCollection 并删除 NotifyPropertyChanged 处理程序后,一切正常。
这正是为什么ObservableCollection<T>
班级介绍...ObservableCollection<T>
实施INotifyCollectionChanged
,这使得它可以在添加/删除/替换项目时通知 UI。List<T>
不会触发任何通知,因此 UI 无法检测到列表内容何时发生更改。
事实上,你提出了PropertyChanged
事件确实刷新了绑定,但随后它意识到它是同一个实例List<T>
和以前一样,所以它重用了相同的ICollectionView
as the ItemsSource
,以及内容ListBox
没有刷新。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)