2015-06-16 45 views
1

我有一個包含我的客戶的詳細信息的類。綁定的WinForms ListBox中收集到列表<object>

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

    // Lots of other properties configured. 
} 

我也有CustomerDataList<CustomerData> MyData;

的名單我現在databinding個人CustomerData對象textboxes在正常工作下面的方法。

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

我努力尋找到列表中的每個MyData對象綁定到一個ListBox的方式。

我想讓MyData列表中的每個對象顯示在顯示名稱的列表框中。

我已經嘗試設置DataSource等於MyData列表和設置DisplayMember到「姓名」然而,當我將項目添加到MyData列表listbox不會更新。

有關如何完成的任何想法?

+2

你檢查這一點:http://stackoverflow.com/questions/2675067/binding-listbox-to-listobject? –

+0

是的,我已經試過了。但是,當我添加項目到我的列表ListBox不更新。 – CathalMF

+2

winforms不使用觀察系統。因此你必須將對象推送到列表框本身。 – JSJ

回答

1

我發現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. 
相關問題