我正在做一个Windows窗体应用程序,我有以下类:
Person.cs
class Person
{
public string name{ get; set; }
public Person(string name)
{
this.name = name;
}
}
Repository.cs
class Repository
{
private static instance;
private Repository()
{
persons= new List<Person>();
}
public static Instance
{
get
{
if (instance == null)
{
instance = new Repository();
}
return instance;
}
}
private List<Person> videos;
public List<Person> getVideos()
{
return videos;
}
}
我想将ListBox
中的Form
绑定到我的存储库中的人员列表。
我该怎么做?我正在尝试使用设计器执行此操作,我在DataSource
中有字段ListBox
,是否将其与Person
或Repository
类绑定? cass的领域必须公开吗?绑定后,我添加到我的存储库的任何数据都会自动显示在我的ListBox
?
答案 0 :(得分:1)
以下是将List<T>
数据绑定到ListBox
的绝对最小示例:
class Person
{
public string Name{ get; set; } // the property we need for binding
public Person(string name) { Name = name; } // a constructor for convenience
public override string ToString() { return Name; } // necessary to show in ListBox
}
class Repository
{
public List<Person> persons { get; set; }
public Repository() { persons = new List<Person>(); }
}
private void button1_Click(object sender, EventArgs e)
{
Repository rep = new Repository(); // set up the repository
rep.persons.Add(new Person("Tom Jones")); // add a value
listBox1.DataSource = rep.persons; // bind to a List<T>
}
注意:由于多种原因,显示屏会在DataSource
的每次更改时不更新,最明显的是性能。我们可以用这样的最小方式控制刷新:
private void button2_Click(object sender, EventArgs e)
{
rep.persons.Add(new Person("Tom Riddle"));
listBox1.DataSource = null;
listBox1.DataSource = rep.persons;
}
稍微扩展示例,使用BindingSource
我们可以调用ResetBindings
来更新如下所示的项目:
private void button1_Click(object sender, EventArgs e)
{
rep.persons.Add(new Person("Tom Jones"));
rep.persons.Add(new Person("Tom Hanks"));
BindingSource bs = new BindingSource(rep, "persons");
listBox1.DataSource = bs;
}
private void button2_Click(object sender, EventArgs e)
{
rep.persons.Add(new Person("Tom Riddle"));
BindingSource bs = (BindingSource)listBox1.DataSource;
bs.ResetBindings(false);
}