如何将 ComboBox 绑定到具有深层 DisplayMember 和 ValueMember 属性的通用列表?
我正在尝试将一个通用列表(如列表父级)绑定到组合框。
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”显示在我的组合框中,而不是“SHOW THIS”。 如何通过一级或更深的属性(例如 child.DisplayMember)将 ComboBox 绑定到通用列表?
提前致谢, 阿道夫
I am trying to bind a generic list like List Parents to a 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; }
}
When I run my test app I only see: "ComboBindingToListTest.Parent" displayed in my ComboBox instead of "SHOW THIS".
How can I bind a ComboBox to a Generic List through one level or deeper properties e.g. child.DisplayMember??
Thanks in Advance,
Adolfo
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不认为你能做你想做的事。上面的设计表明,父母只能有一个孩子。这是真的吗?或者您是否为了这个问题而简化了设计?
无论父级是否可以有多个子级,我建议您使用匿名类型作为组合框的数据源,并使用 linq 填充该类型。这是一个例子:
I don't think you can do what you ar attempting. The design above shows that a Parent can only have one child. Is that true? Or have you simplified the design for the purpose of this question.
What I would recommend, regardless of whether a parent can have multiple children, is that you use an anonymous type as the Data Source for the combo box, and populate that type using linq. Here is an example:
这样就可以完成工作:
如果 Children 在父类中,那么您可以简单地使用:
但是,如果您需要绑定到多个父类的子类,您可以执行以下操作:
That will do the job:
If Children was in a parent class, then you can simply use:
However, if you need to bind to the children of multiple parents you can do the following:
您可以拦截数据源更改事件并在其中进行特定的对象绑定。
You could just intercept the datasource changed event and do specific object bindings in there.