Dam*_*ian 11 c# wpf binding listbox observablecollection
我有一节课:
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));
}
}
}
Run Code Online (Sandbox Code Playgroud)
和绑定(UserControl的DataContext是A的实例):
<ListBox ItemsSource="{Binding Path=bList}" />
Run Code Online (Sandbox Code Playgroud)
显示元素,新对象添加到List后ListBox不会更新
将列表更改为ObservableCollection并删除NotifyPropertyChanged处理程序后,一切正常.
为什么列表不起作用?
Tho*_*que 16
您的属性必须是public,或绑定引擎将无法访问它.
编辑:
将列表更改为ObservableCollection并删除NotifyPropertyChanged处理程序后,一切正常.
这正是ObservableCollection<T>引入类的原因...... ObservableCollection<T>实现INotifyCollectionChanged,它允许它在添加/删除/替换项目时通知UI.List<T>不会触发任何通知,因此UI无法检测列表内容何时发生更改.
你提高的事实,PropertyChanged事件不会刷新绑定,但后来意识到它是相同的实例List<T>和以前一样,所以重复使用相同ICollectionView的ItemsSource,和的内容ListBox不被刷新.