C# 重写 CheckedBoxList 显示成员

C# Override CheckedBoxList Display Member

有没有办法为 CheckedListBox 设置多列显示成员,而无需创建新的 class 将属性值合并在一起?例如重写 DisplayMember?

我正在使用 C# 4.0 VS 2015

您不需要覆盖 DisplayMember。相反,您可以处理 CheckedListBoxFormat 事件,这样您就可以为每个元素提供自定义显示值。

The Format event is raised before each visible item in the ListControl is formatted. Handling this event gives you access to the string to be displayed for this list item, through the Value property of the ListControlConvertEventArgs.

事件的event参数,包含一个ListItem 属性是item后面的对象,所以你可以在这里混合一些属性并将结果赋值给e.Value

例如,假设您在 checkedListBox1 中显示 List<Product>,我们可以通过这种方式简单地自定义外观:

private void checkedListBox1_Format(object sender, ListControlConvertEventArgs e)
{
    var p = (Product)e.ListItem;
    e.Value = string.Format("Name: {0}, Price: {1}", p.Name, p.Price);
}