我希望能够将列表绑定到ListBox数据源中,当列表被修改时,ListBox的UI会自动更新。(Winforms而非ASP)。以下是一个示例:
private List<Foo> fooList = new List<Foo>();
private void Form1_Load(object sender, EventArgs e)
{
//Add first Foo in fooList
Foo foo1 = new Foo("bar1");
fooList.Add(foo1);
//Bind fooList to the listBox
listBox1.DataSource = fooList;
//I can see bar1 in the listbox as expected
}
private void button1_Click(object sender, EventArgs e)
{
//Add anthoter Foo in fooList
Foo foo2 = new Foo("bar2");
fooList.Add(foo2);
//I expect the listBox UI to be updated thanks to INotifyPropertyChanged, but it's not
}
class Foo : INotifyPropertyChanged
{
private string bar_ ;
public string Bar
{
get { return bar_; }
set
{
bar_ = value;
NotifyPropertyChanged("Bar");
}
}
public Foo(string bar)
{
this.Bar = bar;
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
public override string ToString()
{
return bar_;
}
}
如果我用
BindingList<Foo> fooList = new BindingList<Foo>();
替换List<Foo> fooList = new List<Foo>();
,那么它就能工作。但是我不想改变foolist的原始类型。我想让像这样的东西工作:listBox1.DataSource = new BindingList<Foo>(fooList);
编辑:我刚刚在List<T> vs BindingList<T> Advantages/DisAdvantages中读到了Ilia Jerebtsov的话:“当您将BindingSource的DataSource设置为List时,它会在内部创建一个BindingList来包装您的列表”。我认为我的示例只是说明这不是真的:我的List<>似乎没有内部包装成BindingList<>。