在ComboBox中以粗体显示一些项目

时间:2012-03-29 06:54:35

标签: winforms

我的Windows应用程序中有一个组合框,它是DataBound到一个只读列表。我的要求是根据列表的属性显示Bold中的一些项目。该属性与value member和Display Member的属性不同。无论如何都没有循环遍历每个项目,因为列表太大了?

1 个答案:

答案 0 :(得分:2)

关闭所选项目。

public Form1()
{
    _dataItems = new List<DataItem>
        {
            new DataItem {Name = "Alpha", IsBold = true, OtherData = new object()},
            new DataItem {Name = "Beta", IsBold = false, OtherData = new object()},
            new DataItem {Name = "Gamma", IsBold = true, OtherData = new object()},
        };

    this.InitializeComponent();

    comboBox1.DrawItem += comboBox1_DrawItem;

    comboBox1.DataSource = _dataItems;
    comboBox1.DisplayMember = "Name";
    comboBox1.ValueMember = "OtherData";
}

void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
{
    var dataItem = (DataItem)comboBox1.Items[e.Index];

    if (dataItem.IsBold)
        e.Graphics.DrawString(dataItem.Name, BoldFont, SystemBrushes.ControlText,
                            e.Bounds);
    else
        e.Graphics.DrawString(dataItem.Name, NormalFont, SystemBrushes.ControlText,
                            e.Bounds);
}

DataItem类:

public class DataItem
{
    public String Name { get; set; }
    public bool IsBold { get; set; }
    public Object OtherData { get; set; }

    public override string ToString()
    {
        return Name;
    }
}