如何解决如何将ComboBox绑定到具有深色DisplayMember和ValueMember属性的通用列表?
| 我正在尝试将通用列表(如“列表父母”)绑定到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; }
}
运行测试应用程序时,我只会在ComboBox中看到\“ ComboBindingToListTest.Parent \”,而不是\“ SHOW THIS \”。
如何通过一个或更深级别的属性将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;
}
,这样就可以了:
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;
,您可以截获数据源更改的事件,然后在其中进行特定的对象绑定。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。