简体   繁体   English

将 Winforms ListBox 集合绑定到列表<object>

[英]Bind Winforms ListBox collection to List<object>

I have a class containing details of my customer.我有一个包含客户详细信息的类。

class CustomerData : INotifyPropertyChanged
{
    private string _Name;
    public string Name 
    { 
        get 
        { return _Name } 
        set 
        {
            _Name = value;
            OnPropertyChanged("Name");
        }
    }

   // Lots of other properties configured.
}

I also have a list of CustomerData values List<CustomerData> MyData;我还有一个CustomerDataList<CustomerData> MyData;

I currently databinding an individual CustomerData object to textboxes in the below way which works fine.我目前以以下方式将单个CustomerData对象databindingtextboxes ,效果很好。

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

I'm struggling to find a way to bind each object in the list MyData to a ListBox .我正在努力寻找一种方法将列表MyData中的每个对象绑定到ListBox

I want to have each object in the MyData list in displayed in the ListBox showing the name.我想让 MyData 列表中的每个对象显示在显示名称的 ListBox 中。

I have tried setting the DataSource equal to the MyData list and setting the DisplayMember to "Name" however when i add items to the MyData list the listbox does not update.我曾尝试将DataSource设置为等于MyData列表并将DisplayMember设置为“Name”,但是当我将项目添加到MyData列表时, listbox不会更新。

Any ideas on how this is done?关于如何做到这一点的任何想法?

I found that List<T> will not allow updating of a ListBox when the bound list is modified.我发现List<T>将不允许在修改绑定列表时更新 ListBox。 In order to get this to work you need to use BindingList<T>为了BindingList<T>工作,你需要使用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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM