将对象绑定到ListBox [英] Bind object to ListBox
问题描述
我正在做Windows窗体应用程序,我有以下课程:
I am doing a Windows Form Application and I have the following classes:
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;
}
}
我想将Form
中的ListBox
绑定到存储库中的人员列表.
I want to bind a ListBox
in my Form
to the list of persons in my repository.
我该怎么做?我正在尝试使用设计器执行此操作,我的ListBox
中有字段DataSource
,是否将其与我的Person
或Repository
类绑定? cass的字段必须是公共的?绑定后,我添加到存储库中的所有数据都会自动出现在我的ListBox
?
How can I do that? I am trying to do that using the designer, I have the field DataSource
in my ListBox
, do I bind it with my Person
or Repository
class? The fields of the cass must be public? After the binding any data I add to my repository will automatically appear in my ListBox
?
推荐答案
以下是将List<T>
绑定到ListBox
的绝对最小示例:
Here is an absolutely minimal example of databinding a List<T>
to a 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
的每次更改,显示屏都不会不更新,其中最显着的原因是性能.我们可以通过以下最小方式控制刷新:
Note: The display will not update on each change to the DataSource
for several reasons, most notably for performance. We can control the refresh, in a minimal way like this:
private void button2_Click(object sender, EventArgs e)
{
rep.persons.Add(new Person("Tom Riddle"));
listBox1.DataSource = null;
listBox1.DataSource = rep.persons;
}
使用BindingSource
稍微扩展示例,我们可以调用ResetBindings
来更新如下所示的项目:
Expanding the example a little, using a BindingSource
we can, among other things, call ResetBindings
to update the items shown like this:
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);
}
这篇关于将对象绑定到ListBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!