在 C# 中通过代码设置列表框项的字体和颜色 [英] Set the font and color of a listbox item by code in C#

查看:11
本文介绍了在 C# 中通过代码设置列表框项的字体和颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正忙于一个自定义列表框,我在 C# 中用作寄存器阅读器.现在我想在一个确定的项目中设置一个确定的项目,其字体和颜色与其他项目不同.我检查了 这个问题 并从我所做的答案中以下代码:

I'm busy with a customized list box that I use as a register reader in c#. Now I want to set a determined item in a determined item with a different font and color than the rest. I checked This question and from the answers I made the following code:

private void myListBox_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e)
{
    e.DrawBackground();
    Font myFont;
    Brush myBrush;
    int i = e.Index;

    if (e.Index == 3)
    {
        myFont = e.Font;
        myBrush = Brushes.Black;
    }
    else
    {
        myFont = new Font("Microsoft Sans Serif", 9.75f, FontStyle.Bold);
        myBrush = Brushes.CadetBlue;
    }

    e.Graphics.DrawString(myListBox.Items[i].ToString(), myFont, myBrush, e.Bounds, StringFormat.GenericDefault);
}

然后在我的 IntializeComponent() 中调用方法

And call the method in my IntializeComponent() using

this.myListBox.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.myListBox_DrawItem);

该调用不会引发任何异常,但我看不到我想要处理的行有任何变化.有什么我遗漏的吗?

The call does not throw an exception whatsoever, but I see no change on the line I want to handle. Is there something I am missing?

推荐答案

您的 IntializeComponent() 中又少了一行:

You are missing one more line in your IntializeComponent() add this:

this.myListBox.DrawMode = DrawMode.OwnerDrawFixed;

在附加事件之前.

这篇关于在 C# 中通过代码设置列表框项的字体和颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆