2013-06-18 109 views
0

我具有表示客戶端的對象,並且該對象具有客戶端分支的列表:組合框不更新

private List<Branch> _branches; 
[System.Xml.Serialization.XmlArray("Branches"), System.Xml.Serialization.XmlArrayItem(typeof(Branch))] 
public List<Branch> Branches 
{ 
    get { return _branches; } 
    set 
    { 
     _branches = value; 
     if (this.PropertyChanged != null) 
     { 
      this.PropertyChanged(this, new PropertyChangedEventArgs("Branches")); 
     } 
    } 
} 

在一種形式中(的WinForms)我有一個ComboBox那我綁定到列表:

// creating a binding list for the branches 
var bindingList = new BindingList<Branch>(Client.Branches); 

// bind list to combo box 
cmbBranches.DataSource = bindingList; 
cmbBranches.DisplayMember = "Name"; 
cmbBranches.ValueMember = "Name"; 

在另一個功能,我創建了一個新的Branch對象,並將其添加到現有列表:Client.Branches.Add(newBranch)。我希望這會更新組合框,但它不會。爲什麼不,以及如何更新? (編輯:我也希望在從列表中刪除一個對象時進行更新,我認爲它不起作用的原因是,當調用Add時,爲什麼不更新該框。)

在做研究時,我發現了這個答案,這似乎暗示它會起作用。我覺得我失去了一些東西簡單...

difference between ObservableCollection and BindingList

編輯:什麼,我已經嘗試了一些進一步的信息和一些額外的目標。

我不能使用ObservableCollection<T>而不是List<T>,因爲我需要在代碼中使用Exists。前者沒有。

除了更新下拉框外,我還需要在添加新對象時更新原始列表。

下面來總結一下我的意見,我試圖加入這個:

var bindingList = (BindingList<Branch>) cmbBranches.DataSource; 
bindingList.Add(frmAddBranch.NewBranch); 

但是,這導致對象被添加到組合框的兩倍。不知何故,通過調用bindingList.Add它是「重置」數據源並翻倍。我無法找到任何一旦綁定就「刷新」數據顯示的功能。 Control.ResetBindings()沒有工作。

+0

看看這是否有幫助http://stackoverflow.com/questions/13575397/cant-figure-out-how-to-convert-class-strings-to-a-datagrid/13575912#13575912 –

+0

等等,所以我需要然後將該成員添加到'bindingList'?這是有道理的...... –

+0

@MPatel - 我添加了這段代碼,現在新對象出現在ComboList中兩次了! 'var bindingList =(BindingList )cmbBranches.DataSource; bindingList.Add(frmAddBranch.NewBranch);' –

回答

1

那麼,它不會那樣工作。內部List<T>沒有更改通知機制,所以直接添加到內部List<T>將不會生成任何最終將到達組合框的更改通知。最方便的做法是通過BindingList<T>來添加項目。

+0

請參閱我上次對MPatel的最後一條評論...導致對象被添加兩次到ComboBox。 –

+0

你忘了刪除舊的'Client.Branches.Add(newBranch)'嗎? – tia

+0

對於其餘的代碼,它也需要成爲該列表的一部分... –

0

我相信你必須直接添加項目到BindingList(但不支持Branches列表 - BindingList應該爲你照顧)。