当对象添加到绑定列表时,ComboBox不会更新

时间:2013-06-18 18:07:57

标签: c# winforms bindinglist

我有一个代表客户端的对象,该对象有一个客户端分支列表:

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,但它不会。为什么不,我如何更新它? (编辑:我也希望在从列表中删除对象时进行更新。我认为,它不起作用的原因与{{{} {{{ 1}}被称为。)

在做研究时,我发现了这个答案,这似乎意味着它会起作用。我觉得我错过了一些简单的事情......

difference between ObservableCollection and BindingList

修改:有关我尝试过的内容以及其他一些目标的更多信息。

我无法使用Add代替ObservableCollection<T>,因为我需要在代码中使用List<T>。前者没有。

除了更新下拉框之外,我还需要在添加新对象时更新原始列表。

总结下面的评论,我尝试添加:

Exists

但是这导致对象被添加到ComboBox两次。不知怎的,通过致电var bindingList = (BindingList<Branch>) cmbBranches.DataSource; bindingList.Add(frmAddBranch.NewBranch); 它&#34;重置&#34;数据源并加倍。我找不到任何&#34;刷新&#34;一旦受到约束,数据就会显示出来。 bindingList.Add无效。

2 个答案:

答案 0 :(得分:1)

嗯,这样做不行。内部List<T>没有更改通知机制,因此直接添加到内部List<T>将不会生成任何最终会到达组合框的更改通知。最方便的做法是通过BindingList<T>添加项目。

答案 1 :(得分:0)

我认为您必须将这些项目直接添加到BindingList(但不能添加到支持Branches列表中 - BindingList应该为您处理此事。)

相关问题