【发布时间】:2013-06-18 18:07:56
【问题描述】:
我有一个代表客户的对象,该对象有一个客户分支的列表:
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 时框不更新直接相关。)
在做研究时,我发现了这个 SO 答案,这似乎暗示它会起作用。我觉得我错过了一些简单的东西......
difference between ObservableCollection and BindingList
编辑:一些关于我尝试过的东西和一些额外目标的更多信息。
我不能使用ObservableCollection<T> 代替List<T>,因为我需要在代码中使用Exists。前者没有。
我需要在添加新对象时更新原始列表,除了更新下拉框。
为了总结下面的 cmets,我尝试添加以下内容:
var bindingList = (BindingList<Branch>) cmbBranches.DataSource;
bindingList.Add(frmAddBranch.NewBranch);
但这会导致对象被两次添加到 ComboBox 中。不知何故,通过调用bindingList.Add,它正在“重置”数据源并加倍。一旦绑定,我找不到任何“刷新”数据显示的功能。 Control.ResetBindings() 无效。
【问题讨论】:
-
等等,所以我需要然后将成员添加到
bindingList?这是有道理的...... -
@MPatel - 我添加了这段代码,现在新对象出现在 ComboList 中两次!
var bindingList = (BindingList<Branch>) cmbBranches.DataSource; bindingList.Add(frmAddBranch.NewBranch);
标签: c# winforms bindinglist