C# 如何给列表框项目着色?

C# 如何给列表框项目着色?,c#,winforms,listbox,C#,Winforms,Listbox,我想更改列表框项目的颜色。我的代码似乎不起作用。 它只是将类的名称空间添加到ListBox项中 将项目添加到列表框的代码: 这会将一个项目添加到列表框的黑色AddFoldersToClientFolder.myListboxItem中。您可以使用列表框事件: private void listBox1_DrawItem(object sender, DrawItemEventArgs e) { var item = (myListboxItem)listBox1.Items[e.Inde

我想更改列表框项目的颜色。我的代码似乎不起作用。 它只是将类的名称空间添加到ListBox项中

将项目添加到列表框的代码:

这会将一个项目添加到列表框的黑色AddFoldersToClientFolder.myListboxItem中。

您可以使用列表框事件:

private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
    var item = (myListboxItem)listBox1.Items[e.Index];
    e.DrawBackground();

    using (var brush = new SolidBrush(item.ItemColor))
        e.Graphics.DrawString(item.Message, listBox1.Font, brush, e.Bounds);
}
注意:您还需要将ListBox的事件设置为DrawMode.OwnerDrawFixed或DrawMode.OwnerDrawVariable

您可以使用ListBox的事件:

private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
    var item = (myListboxItem)listBox1.Items[e.Index];
    e.DrawBackground();

    using (var brush = new SolidBrush(item.ItemColor))
        e.Graphics.DrawString(item.Message, listBox1.Font, brush, e.Bounds);
}

注意:您还需要将ListBox设置为DrawMode.OwnerDrawFixed或DrawMode.OwnerDrawVariable

谢谢您的回答,我收到一个错误,说索引无效?此外,我不明白如何将此应用于特定项而不是所有列表框项?感谢您的回答,我收到一个错误,说索引无效?此外,我不明白如何将此应用于特定项而不是所有列表框项?
private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
    var item = (myListboxItem)listBox1.Items[e.Index];
    e.DrawBackground();

    using (var brush = new SolidBrush(item.ItemColor))
        e.Graphics.DrawString(item.Message, listBox1.Font, brush, e.Bounds);
}