简体   繁体   English

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

[英]Set the font and color of a listbox item by code in C#

I'm busy with a customized list box that I use as a register reader in c#. 我正忙于一个自定义列表框,我在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);
}

And call the method in my IntializeComponent() using 并使用我的IntializeComponent()调用该方法

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? 有什么我想念的吗?

You are missing one more line in your IntializeComponent() add this: 您在IntializeComponent()中缺少一行,添加以下内容:

this.myListBox.DrawMode = DrawMode.OwnerDrawFixed;

before attaching an event. 在附上活动之前。

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

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