listBox.DataSource = bindingSource;
listBox.DisplayMember = "propertyName";
上面代码中的DisplayMember就是设置将数据源中对象的哪个属性显示出来。这里需要注意,DisplayMember只能对应到对象的属性(Property)上,不能设置为对象的字段(Field),即使公共字段也不行。对于下面这个对象:
internal class TestBinding
{
public string publicField;
private string publicProperty;
public string PublicProperty
{
get { return publicProperty; }
set { publicProperty = value; }
}
}
如果我们设置绑定:
listSubsetHeaders.DisplayMember = "publicField"; //failed:bind to public field
listSubsetHeaders.DisplayMember = "PublicProperty"; //ok: bind to property
DataBind不允许绑定到公共字段上,必须绑定到属性才行:
One of the reasons why data-binding support is limited to properties happens to
be the fact that all of data-binding is built around PropertyDescriptors and not
on direct reflection.
这里有篇blog讨论了这个问题:Data-binding to public fields... yes or no?
没有评论:
发表评论