加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何将ComboBox绑定到具有深DisplayMember和ValueMember属

发布时间:2020-12-15 04:22:35 所属栏目:百科 来源:网络整理
导读:我试图将列表父项之类的通用列表绑定到ComboBox. public Form1() { InitializeComponent(); ListParent parents = new ListParent(); Parent p = new Parent(); p.child = new Child(); p.child.DisplayMember="SHOW THIS"; p.child.ValueMember = 666; pare
我试图将列表父项之类的通用列表绑定到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?

提前致谢,
阿道夫

解决方法

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读