![](/img/trans.png)
[英]WPF Combobox selection disappears when the an item is deleted in the list bound to combobox
[英]ComboBox not updating when object added to bound list
我有一個代表客戶端的對象,並且該對象具有客戶端分支的列表:
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)
。 我希望這會更新ComboBox,但不會。 為什么不呢,我該如何更新呢? (編輯:當我從列表中刪除一個對象時,我也希望此更新。我認為它不起作用的原因與調用Add
時該框未更新的原因直接相關。)
在進行研究時,我找到了這樣的答案,這似乎暗示它會起作用。 我覺得我缺少一些簡單的東西...
ObservableCollection和BindingList之間的區別
編輯:有關我嘗試過的內容和一些其他目標的更多信息。
我不能使用ObservableCollection<T>
代替List<T>
因為我需要在代碼中使用Exists
。 前者沒有。
添加新對象時,除了更新下拉框之外,我還需要更新原始列表。
為了在下面總結我的評論,我嘗試添加以下內容:
var bindingList = (BindingList<Branch>) cmbBranches.DataSource;
bindingList.Add(frmAddBranch.NewBranch);
但這導致該對象兩次添加到ComboBox。 通過調用bindingList.Add
某種方式“重置”數據源並加倍。 綁定數據后,我找不到任何“刷新”數據顯示的功能。 Control.ResetBindings()
無法正常工作。
好吧,這種方式行不通。 內部List<T>
沒有更改通知機制,因此直接添加到內部List<T>
不會生成任何更改通知,這些更改通知最終將到達組合框。 執行所需操作的最便捷方法是通過BindingList<T>
添加項目。
我相信您必須將這些項目直接添加到BindingList
(而不是添加到支持的Branches
列表中BindingList
應該為您處理)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.