【问题标题】:Databinding combobox to empty List<CustomObject>将数据绑定组合框清空 List<CustomObject>
【发布时间】:2013-12-12 22:07:09
【问题描述】:

我有一个包含两个 ComboBox 的表单。我想使用第二个(子)ComboBox 根据用户对第一个项目的选择来显示子对象列表。

当窗体实例化时,我将两个控件数据绑定到私有 List,如下所示:

private List<ParentWidget> _parentList;
private List<ChildWidget> _childList;

public FormExample()
{
    InitializeComponent();

    _parentList = GetParentWidgets();
    _childList = new List<ChildWidget>();

    cmbParent.DisplayMember = "WidgetName";
    cmbParent.ValueMember = "ID";
    cmbParent.DataSource = _parentList;

    cmbChild.DisplayMember = "WidgetName";
    cmbChild.ValueMember = "ID";
    cmbChild.DataSource = _childList;
}

当父选择的索引发生变化时,我会用适当的对象填充_childList

问题是子 ComboBox 从不显示集合中的任何对象。如果我在数据绑定之前用至少一个 ChildWidget 填充集合,它会起作用,但我希望它从空开始。

如果我从another answer 中正确理解,这将失败,因为空列表不包含任何要绑定的属性。但是,我绑定到特定类(Widget)而不是通用对象。这对数据绑定来说还不够吗?

【问题讨论】:

    标签: c# winforms data-binding


    【解决方案1】:

    在使用绑定的时候最好用BindingList&lt;&gt;代替,你的问题是List&lt;&gt;不支持通知变化,所以当数据发生变化时,控件不知道并相应更新。您可以像这样使用BindingList&lt;&gt;

    private BindingList<ParentWidget> _parentList;
    private BindingList<ChildWidget> _childList;
    

    这意味着你必须将方法GetParentWidgets()的返回类型更改为BindingList&lt;ParentWidget&gt;,或者你也可以像这样使用BindingList&lt;&gt;的构造函数:

    _parentList = new BindingList<ParentWidget>(GetParentWidgets());
    

    【讨论】:

    • 是否可以通过将ComboBox绑定到BindingSource并将BindingSource的DataSource设置为原始List来实现相同的行为?
    • @JYelton 我认为BindingSource 可以,但是您必须将新项目添加到BindingSource 本身,而不是List&lt;&gt;,使用BindingList&lt;&gt; 还需要您将项目添加到BindingList&lt;&gt; 不是 List&lt;&gt;
    【解决方案2】:

    我要做的是监听父组合框的 valueChanged 事件,当事件触发时,我会对子组合框进行数据绑定。

    cmbParent.SelectedValueChanged += OnParentSelectedValueChanged;
    
    private void OnParentSelectedValueChanged(object sender, EventArgs e)
    {
        this.UpdateChildList(); // Update the data depending on the value in the parent combo
    
        cmbChild.DisplayMember = "WidgetName"; // I guess you can still do this in the constructor
        cmbChild.ValueMember = "ID"; // I guess you can still do this in the constructor
    
        cmbChild.DataSource = _childList;   
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-26
      • 1970-01-01
      • 1970-01-01
      • 2013-01-28
      • 1970-01-01
      • 1970-01-01
      • 2016-05-02
      • 2012-01-24
      相关资源
      最近更新 更多