簡體   English   中英

按C#中的代碼設置列表框項的字體和顏色

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

我正忙於一個自定義列表框,我在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);
}

並使用我的IntializeComponent()調用該方法

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

該調用不會拋出任何異常,但我看到我想要處理的行沒有變化。 有什么我想念的嗎?

您在IntializeComponent()中缺少一行,添加以下內容:

this.myListBox.DrawMode = DrawMode.OwnerDrawFixed;

在附上活動之前。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM