将Winforms ListBox绑定到List<object>集合

3
我有一个包含客户详细信息的类。
class CustomerData : INotifyPropertyChanged
{
    private string _Name;
    public string Name 
    { 
        get 
        { return _Name } 
        set 
        {
            _Name = value;
            OnPropertyChanged("Name");
        }
    }

   // Lots of other properties configured.
}

我还有一个 CustomerData 值的列表 List<CustomerData> MyData;

目前我通过以下方式将单个 CustomerData 对象绑定到 textboxes 中,这种方法运行良好。

this.NameTxtBox.DataBindings.Add("Text", MyCustomer, "Name", false, DataSourceUpdateMode.OnPropertyChanged);

我很难找到一种将列表MyData中的每个对象绑定到ListBox的方法。我希望在ListBox中显示MyData列表中的每个对象名称。我尝试将DataSource设置为MyData列表,并将DisplayMember设置为“Name”,但是当我向MyData列表添加项目时,listbox没有更新。您有任何想法如何完成这个操作吗?

2
你有检查过这个链接吗:https://dev59.com/GHE85IYBdhLWcg3wpFSu? - George Vovos
是的,我已经尝试过了。但是当我向我的列表中添加项目时,ListBox没有更新。 - CathalMF
2
WinForms不使用观察系统,因此您必须将对象推送到ListBox本身。 - JSJ
1
找到了。我需要使用BindingList<T>而不是List<T>。这样可以使ListBox在集合修改时更新。 - CathalMF
1个回答

4

我发现当绑定的列表被修改时,List<T> 无法更新 ListBox。为了让它正常工作,你需要使用 BindingList<T>

BindingList<CustomerData> MyData = new BindingList<CustomerData>();

MyListBox.DataSource = MyData;
MyListBox.DisplayMember = "Name";

MyData.Add(new CustomerData(){ Name = "Jimmy" } ); //<-- This causes the ListBox to update with the new entry Jimmy.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接