【问题标题】:Bind object to ListBox将对象绑定到 ListBox
【发布时间】:2015-10-31 11:02:49
【问题描述】:

我正在做一个 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;
    }
}

我想将我的Form 中的ListBox 绑定到我的存储库中的人员列表。

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

【问题讨论】:

  • 对不起,Repository 类是一个单例,当我在帖子中格式化代码时发生了错误。私有属性实际上是一个私有字段,但我在某处读到,为了绑定我需要属性,所以我更改了它,但没有更改访问器。

标签: c# winforms binding


【解决方案1】:

这是一个绝对最小的示例,将List&lt;T&gt; 数据绑定到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);
}

【讨论】:

  • 如果我在 Repository 类的列表中添加数据,ListBox 会自动更新吗?
  • 否,要么使用 BindingSource,要么简单地“手动”重置数据源。查看更新!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-12-21
  • 1970-01-01
  • 2013-02-20
  • 2012-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多