Highlighting a particular item in a combo box

孤街醉人 提交于 2019-12-24 03:39:10

问题


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.


回答1:


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):

I have populated the combobox with Template objects, defined like this:

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:

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.




回答2:


Set combo box's DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable. And, Override Combobox_MeasureItem() and Combobox_DrawItem() methods, to achieve this.



来源:https://stackoverflow.com/questions/856397/highlighting-a-particular-item-in-a-combo-box

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!