簡體   English   中英

在 C# 中,如何使列表框中的所有項目不更改為我最后設置的顏色?

[英]In C#, how can I keep all my items in a listbox from changing to the color I set last?

我已經研究了如何更改每一行的顏色,這是我使用公共變量 itemColor 的代碼,它是一個 Brush

...

public Brush itemColor;

private void button2_Click(object sender, EventArgs e)
{
    itemColor = Brushes.Purple;
    listBox1.Items.Add("Purple");
    itemColor = Brushes.Green;
    listBox1.Items.Add("Green");
    itemColor = Brushes.Red;
    listBox1.Items.Add("Red");
}

private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
    e.DrawBackground();
    e.Graphics.DrawString(listBox1.Items[e.Index].ToString(), listBox1.Font, 
                          itemColor, e.Bounds, StringFormat.GenericDefault);
    e.DrawFocusRectangle();
}

...

我已將列表框 DrawMode 設置為 OwnerDrawFixed,並且所有項目都變為紅色。 誰能看到我可能很愚蠢的錯誤?

每次需要重繪控件時都會調用listBox1_DrawItem ,例如在項目添加/刪除或選擇更改時。 您可以通過向表單添加第二個按鈕並執行以下操作來查看這一點:

private void button2_Click(object sender, EventArgs e)
{
    itemColor = Brushes.Blue;
}

單擊第二個按鈕后,下次重繪ListBox ,所有項目的文本都將變為藍色。


很可能有一種更好的方法來做到這一點,但您可以處理這個問題的一種方法是創建一個類來表示您的項目與TextBrush字段並添加填充您的列表框。 然后在 DrawItem 處理程序上,您將Items[e.Index]為您的類並引用文本和顏色字段。 像這樣的東西:

class Entry
{
    public string Text;
    public Brush Color;
}

private void button1_Click(object sender, EventArgs e)
{
    listBox1.Items.Add(new Entry { Text = "Purple", Color = Brushes.Purple });
    listBox1.Items.Add(new Entry { Text = "Green",  Color = Brushes.Green  });
    listBox1.Items.Add(new Entry { Text = "Red",    Color = Brushes.Red    });
}

private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
    var currentItem = listBox1.Items[e.Index] as Entry;

    e.DrawBackground();
    e.Graphics.DrawString(currentItem.Text, listBox1.Font, currentItem.Color,
                          e.Bounds, StringFormat.GenericDefault);
    e.DrawFocusRectangle();
}

暫無
暫無

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

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