按C#中的代码设置列表框项的字体和颜色

Mar*_*nez 4 c# listbox winforms

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

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);
}
Run Code Online (Sandbox Code Playgroud)

并使用我的IntializeComponent()调用该方法

this.myListBox.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.myListBox_DrawItem);
Run Code Online (Sandbox Code Playgroud)

该调用不会抛出任何异常,但我看到我想要处理的行没有变化.有什么我想念的吗?

gza*_*axx 5

您在IntializeComponent()添加此内容时缺少另外一行:

this.myListBox.DrawMode = DrawMode.OwnerDrawFixed;
Run Code Online (Sandbox Code Playgroud)

在附上活动之前.