【问题标题】:ComboBox not updating when object added to bound list将对象添加到绑定列表时组合框不更新
【发布时间】: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&lt;T&gt; 代替List&lt;T&gt;,因为我需要在代码中使用Exists。前者没有。

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

为了总结下面的 cmets,我尝试添加以下内容:

var bindingList = (BindingList<Branch>) cmbBranches.DataSource;
bindingList.Add(frmAddBranch.NewBranch);

但这会导致对象被两次添加到 ComboBox 中。不知何故,通过调用bindingList.Add,它正在“重置”数据源并加倍。一旦绑定,我找不到任何“刷新”数据显示的功能。 Control.ResetBindings() 无效。

【问题讨论】:

  • 等等,所以我需要然后将成员添加到bindingList?这是有道理的......
  • @MPatel - 我添加了这段代码,现在新对象出现在 ComboList 中两次! var bindingList = (BindingList&lt;Branch&gt;) cmbBranches.DataSource; bindingList.Add(frmAddBranch.NewBranch);

标签: c# winforms bindinglist


【解决方案1】:

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

【讨论】:

  • 请看我上面对 MPatel 的最后评论...这导致对象被两次添加到 ComboBox。
  • 您是否忘记删除旧的Client.Branches.Add(newBranch)
  • 如果你必须添加到底层List&lt;T&gt;,你可以在之后调用BindingList&lt;T&gt;.ResetBindings强制更新。
  • 调用BindingList&lt;T&gt;.ResetBindings() 是诀窍。我试图在 ComboBox 上调用 ResetBindings(),而不是绑定列表。已修复,谢谢!
【解决方案2】:

我相信您必须将项目直接添加到 BindingList(但不要添加到支持 Branches 列表 - BindingList 应该为您处理这个问题)。

【讨论】:

    猜你喜欢
    • 2011-04-15
    • 1970-01-01
    • 2014-06-09
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-16
    相关资源
    最近更新 更多