简体   繁体   English

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

[英]Highlighting a particular item in a combo box

I have a scenario where I am populating a combo box with the template names. 我有一个场景,我正在使用模板名称填充组合框。 Amongst the templates one would be a default template. 在模板中,一个是默认模板。 I want to highlight the default template name when I populate the combo box (so that the user knows which one among the items is the default). 我想在填充组合框时突出显示默认模板名称(以便用户知道这些项中的哪一个是默认值)。 Is it possible to do so? 有可能这样做吗? If yes how? 如果有,怎么样? I am using a Windows Form in C# 2.0. 我在C#2.0中使用Windows窗体。

It depends a bit on how you want to hightlight the item. 这取决于你想如何高亮显示项目。 If you want to render the text of the default item in bold, you can achieve that like this (for this to work you need to set the DrawMode of the ComboBox to OwnerDrawFixed , and of course hook up the DrawItem event to the event handler): 如果你想以粗体呈现默认项目的文本,你可以像这样实现(为此你需要将ComboBox的DrawMode设置为OwnerDrawFixed ,当然还要将DrawItem事件连接到事件处理程序) :

I have populated the combobox with Template objects, defined like this: 我用Template对象填充了组合框,定义如下:

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

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

...and the DrawItem event is implemented like this: ...并且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);

    }
}

That should get you going in the right direction, I hope. 我希望,这应该让你朝着正确的方向前进。

Set combo box's DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable. 设置组合框的DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable。 And, Override Combobox_MeasureItem() and Combobox_DrawItem() methods, to achieve this. 并且,覆盖Combobox_MeasureItem()和Combobox_DrawItem()方法,以实现此目的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM