繁体   English   中英

将对象添加到绑定列表时,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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM