【问题标题】:How to bind a ComboBox to a generic List with deep DisplayMember and ValueMember properties?如何将 ComboBox 绑定到具有深层 DisplayMember 和 ValueMember 属性的通用列表?
【发布时间】:2011-08-06 12:35:57
【问题描述】:

我正在尝试将像 List parents 这样的通用列表绑定到 ComboBox。

    public Form1()
    {
        InitializeComponent();
        List<Parent> parents = new List<Parent>();
        Parent p = new Parent();
        p.child = new Child();
        p.child.DisplayMember="SHOW THIS";
        p.child.ValueMember = 666;
        parents.Add(p);
        comboBox1.DisplayMember = "child.DisplayMember";
        comboBox1.ValueMember = "child.ValueMember";
        comboBox1.DataSource = parents;
    }
}
public class Parent
{
    public Child child { get; set; }
}
public class Child
{
    public string DisplayMember { get; set; }
    public int ValueMember { get; set; }
}

当我运行我的测试应用程序时,我只看到:“ComboBindingToListTest.Parent”显示在我的 ComboBox 中,而不是“SHOW THIS”。 如何通过一级或更深的属性将 ComboBox 绑定到通用列表,例如child.DisplayMember??

提前致谢, 阿道夫

【问题讨论】:

    标签: c# winforms binding combobox generic-list


    【解决方案1】:

    您可以只拦截数据源更改事件并在其中进行特定的对象绑定。

    【讨论】:

    • 欢迎来到 Stack Overflow!在回答问题时,请提供有关您的解决方案的详细信息,以便它们对提问者最有用。谢谢!
    【解决方案2】:

    这样就可以了:

    Dictionary<String, String> children = new Dictionary<String, String>();
    children["666"] = "Show THIS";
    
    comboBox1.DataSource = children;
    comboBox1.DataBind();
    

    如果 Children 在父类中,那么您可以简单地使用:

    comboBox1.DataSource = parent.Children;
    ...
    

    但是,如果您需要绑定到多个父母的孩子,您可以执行以下操作:

    var allChildren =
       from parent in parentList
       from child in parent.Children
       select child
    
    comboBox1.DataSource = allChildren;
    

    【讨论】:

      【解决方案3】:

      我不认为你可以做你正在尝试的事情。上面的设计表明一个 Parent 只能有一个孩子。真的吗?或者您是否出于此问题的目的简化了设计。

      无论父级是否可以有多个子级,我都建议您使用匿名类型作为组合框的数据源,并使用 linq 填充该类型。这是一个例子:

      private void Form1_Load(object sender, EventArgs e)
      {
          List<Parent> parents = new List<Parent>();
          Parent p = new Parent();
          p.child = new Child();
          p.child.DisplayMember = "SHOW THIS";
          p.child.ValueMember = 666;
          parents.Add(p);
      
          var children =
              (from parent in parents
                  select new
                  {
                      DisplayMember = parent.child.DisplayMember,
                      ValueMember = parent.child.ValueMember
                  }).ToList();
      
          comboBox1.DisplayMember = "DisplayMember";
          comboBox1.ValueMember = "ValueMember";
          comboBox1.DataSource = children;     
      }
      

      【讨论】:

      • 这很完美@essedbl !!非常感谢。是的,我简化了我的问题,但在我的真实示例中,父母只能有一个孩子。再次感谢
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-04
      • 1970-01-01
      • 1970-01-01
      • 2016-09-25
      相关资源
      最近更新 更多