如何将ComboBox绑定到具有深度DisplayMember和ValueMember属性的通用列表?

6
我正在尝试将一个泛型列表(如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”。如何通过一级或更深的属性(例如child.DisplayMember)将ComboBox绑定到通用列表?
提前致谢, Adolfo
3个回答

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;     
}

这个完美地解决了问题 @essedbl !! 非常感谢你。是的,我简化了我的问题,但在我的真实示例中,父元素只能有一个子元素。再次感谢。 - Adolfo Perez

0

那就可以完成工作了:

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;

0
你可以拦截数据源更改事件,并在其中执行特定的对象绑定。

欢迎来到 Stack Overflow!当回答问题时,请提供有关您的解决方案的详细信息,以便对问题提出者最有帮助。谢谢! - tmesser

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接