如何将ComboBox绑定到具有深DisplayMember和ValueMember属性的泛型List?

时间:2011-04-15 17:35:00

标签: c# winforms binding combobox generic-list

我正在尝试将List Parent这样的通用列表绑定到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中而不是“显示它”。 如何通过一个级别或更深层的属性将ComboBox绑定到通用列表,例如child.DisplayMember ??

先谢谢, 阿道夫

3 个答案:

答案 0 :(得分:8)

我认为你不能做你想做的事。上面的设计表明,父母只能有一个孩子。真的吗?或者你为了这个问题的目的简化了设计。

无论父级是否可以拥有多个子级,我建议您使用匿名类型作为组合框的数据源,并使用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;     
}

答案 1 :(得分:0)

那将完成这项工作:

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

comboBox1.DataSource = children;
comboBox1.DataBind();

如果孩子在父母班级,那么你可以简单地使用:

comboBox1.DataSource = parent.Children;
...

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

var allChildren =
   from parent in parentList
   from child in parent.Children
   select child

comboBox1.DataSource = allChildren;

答案 2 :(得分:0)

您可以截取数据源已更改事件并在其中执行特定对象绑定。