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

标签 c# winforms .net-2.0

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

最佳答案

这在一定程度上取决于您希望如何突出显示该项目。如果您想以粗体呈现默认项目的文本,您可以像这样实现(为此,您需要将 ComboBox 的 DrawMode 设置为 OwnerDrawFixed ,当然还有将 DrawItem 事件连接到事件处理程序):

我用模板对象填充了组合框,定义如下:

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

    }
}

我希望这能让您朝着正确的方向前进。

关于c# - 突出显示组合框中的特定项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/856397/

相关文章:

c# - C#代码隐藏中的多个不同的SQL更新命令

c# - 减少 regex/linq 的 2 GB 内存占用或解决获取不同组值的问题

c# - 重写if语句: One of these statements ended up with one too many pair of braces

C# 使用窗体加载其他用户控件并访问基本控件或属性

c# - 比较数据集或更好的想法

c# - IDisposable 和 ReaderWriterLockSlim

c# - .NET 中的 HTML 布局

c# - 跨线程操作无效 : Control 'label1' accessed from a thread other than the thread it was created on

.net - 在 Windows 窗体中加载与显示事件

c# - 将类型限制为特定类型