将对象绑定到列表框

Bind object to ListBox

我正在做一个 Windows 表格申请,我有以下 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 绑定到我存储库中的人员列表。

我该怎么做?我正在尝试使用设计器来做到这一点,我的 ListBox 中有字段 DataSource,我是否将它与我的 PersonRepository class 绑定? cass的字段必须是public?绑定后,我添加到存储库的任何数据都会自动出现在我的 ListBox?

这是一个 绝对最小的 数据绑定示例 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);
}