在WinForms .Net 3.5中的CheckedListBox中没有DisplayMember的问题可以通过以下方法解决:
ListControl.GetItemText
方法自定义显示文本。public class CustomCheckedListBox : CheckedListBox
{
public CustomCheckedListBox()
{
this.ItemCheck += CustomCheckedListBox_ItemCheck;
}
private void CustomCheckedListBox_ItemCheck(object sender, ItemCheckEventArgs e)
{
e.NewValue = e.CurrentValue;
}
protected override void OnDrawItem(DrawItemEventArgs e)
{
if (e.Index >= 0 && e.Index< Items.Count)
{
object item = Items[e.Index];
string itemText = GetItemText(item);
e.DrawBackground();
using (SolidBrush brush = new SolidBrush(e.ForeColor))
{
e.Graphics.DrawString(itemText, e.Font, brush, e.Bounds);
}
if ((e.State & DrawItemState.Focus) == DrawItemState.Focus)
{
e.DrawFocusRectangle();
}
}
else
{
base.OnDrawItem(e);
}
}
}
ListControl.Format
事件自定义显示文本。public class CustomCheckedListBox : CheckedListBox
{
public CustomCheckedListBox()
{
this.ItemCheck += CustomCheckedListBox_ItemCheck;
this.Format += CustomCheckedListBox_Format;
}
private void CustomCheckedListBox_ItemCheck(object sender, ItemCheckEventArgs e)
{
e.NewValue = e.CurrentValue;
}
private void CustomCheckedListBox_Format(object sender, ListControlConvertEventArgs e)
{
e.Value = GetItemText(e.ListItem);
}
protected override void OnDrawItem(DrawItemEventArgs e)
{
if (e.Index >= 0 && e.Index< Items.Count)
{
object item = Items[e.Index];
string itemText = GetItemText(item);
e.DrawBackground();
using (SolidBrush brush = new SolidBrush(e.ForeColor))
{
e.Graphics.DrawString(itemText, e.Font, brush, e.Bounds);
}
if ((e.State & DrawItemState.Focus) == DrawItemState.Focus)
{
e.DrawFocusRectangle();
}
}
else
{
base.OnDrawItem(e);
}
}
}
这两种方法都可以实现在WinForms .Net 3.5中的CheckedListBox中自定义显示文本。
领取专属 10元无门槛券
手把手带您无忧上云