我希望能够将列表绑定到列表框数据源,并且当修改列表时,列表框的 UI 会自动更新。 (Winform 不是 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_;
}
}
如果我更换List<Foo> fooList = new List<Foo>();
by BindingList<Foo> fooList = new BindingList<Foo>();
然后就可以了。但我不想改变原来的傻子类型。我想要这样的工作:listBox1.DataSource = new BindingList<Foo>(fooList);
编辑:我也刚刚读到这里List 与 BindingList 优点/缺点 https://stackoverflow.com/questions/2243950/listt-vs-bindinglistt-advantages-disadvantages来自 Ilia Jerebtsov :“当您将 BindingSource 的 DataSource 设置为 List 时,它会在内部创建一个 BindingList 来包装您的列表”。我认为我的示例只是表明这不是真的:我的 List 似乎没有在内部包装到 BindingList 中。
你没有绑定源 http://msdn.microsoft.com/en-us/library/system.windows.forms.bindingsource.aspx在你的例子中。
您需要像这样修改它才能使用 BindingSource
var bs = new BindingSource();
Foo foo1 = new Foo("bar1");
fooList.Add(foo1);
bs.DataSource = fooList; //<-- point of interrest
//Bind fooList to the listBox
listBox1.DataSource = bs; //<-- notes it takes the entire bindingSource
Edit
请注意(正如评论中指出的那样)- 绑定源不适用于INotifyPropertyChanged
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)