突出显示组合框中的特定项目

时间:2009-05-13 06:34:28

标签: c# winforms .net-2.0

我有一个场景,我正在使用模板名称填充组合框。在模板中,一个是默认模板。我想在填充组合框时突出显示默认模板名称(以便用户知道这些项中的哪一个是默认值)。有可能这样做吗?如果有,怎么样?我在C#2.0中使用Windows窗体。

2 个答案:

答案 0 :(得分:8)

这取决于您希望如何高亮显示该项目。如果你想以粗体呈现默认项目的文本,你可以像这样实现(为此你需要将ComboBox的DrawMode设置为OwnerDrawFixed,当然还要联系DrawItem事件到事件处理程序):

我已经使用Template对象填充了组合框,定义如下:

private class Template
{
    public string Name { get; set; }
    public bool IsDefault { get; set; }

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

...而DrawItem事件的实现方式如下:

private void ComboBox_DrawItem(object sender, DrawItemEventArgs e)
{
    if (e.Index < 0)
    {
        return;
    }
    Template template = comboBox1.Items[e.Index] as Template;
    if (template != null)
    {

        Font font = comboBox1.Font;
        Brush backgroundColor;
        Brush textColor;

        if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
        {
            backgroundColor = SystemBrushes.Highlight;
            textColor = SystemBrushes.HighlightText;
        }
        else
        {
            backgroundColor = SystemBrushes.Window;
            textColor = SystemBrushes.WindowText;
        }
        if (template.IsDefault)
        {
            font = new Font(font, FontStyle.Bold);
        }
        e.Graphics.FillRectangle(backgroundColor, e.Bounds);
        e.Graphics.DrawString(template.Name, font, textColor, e.Bounds);

    }
}

我希望,这应该让你朝着正确的方向前进。

答案 1 :(得分:0)

设置组合框的DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable。和, 覆盖Combobox_MeasureItem()和Combobox_DrawItem()方法,以实现此目的。

相关问题