将对象绑定到ListBox

时间:2015-10-31 11:02:49

标签: c# winforms binding

我正在做一个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,是否将其与PersonRepository类绑定? cass的领域必须公开吗?绑定后,我添加到我的存储库的任何数据都会自动显示在我的ListBox

1 个答案:

答案 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);
}