我具有表示客戶端的對象,並且該對象具有客戶端分支的列表:組合框不更新
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()
沒有工作。
看看這是否有幫助http://stackoverflow.com/questions/13575397/cant-figure-out-how-to-convert-class-strings-to-a-datagrid/13575912#13575912 –
等等,所以我需要然後將該成員添加到'bindingList'?這是有道理的...... –
@MPatel - 我添加了這段代碼,現在新對象出現在ComboList中兩次了! 'var bindingList =(BindingList)cmbBranches.DataSource; bindingList.Add(frmAddBranch.NewBranch);' –