ListBox项的背景色(winforms)

时间:2020-03-06 14:20:52  来源:igfitidea点击:

如何在System.Windows.Forms.ListBox中设置特定项目的背景颜色?我希望能够设置多个。

解决方案

可能做到这一点的唯一方法是自己绘制项目。

DrawMode设置为OwnerDrawFixed

并在DrawItem事件上编写如下代码:

private void listBox_DrawItem(object sender, DrawItemEventArgs e)
{
    e.DrawBackground();
    Graphics g = e.Graphics;

    g.FillRectangle(new SolidBrush(Color.Silver), e.Bounds);

    // Print text

    e.DrawFocusRectangle();
}

第二种选择是使用ListView,尽管它们还有另一种实现方式(不是真正的数据绑定,但列方式更灵活)

// Set the background to a predefined colour
MyListBox.BackColor = Color.Red;
// OR: Set parts of a color.
MyListBox.BackColor.R = 255;
MyListBox.BackColor.G = 0;
MyListBox.BackColor.B = 0;

如果我们通过设置多种背景色来表示的是为每个项目设置不同的背景色,则对于ListBox而言这是不可能的,但是对于ListView而言则是IS,类似于:

// Set the background of the first item in the list
MyListView.Items[0].BackColor = Color.Red;

感谢Grad van Horck的回答,它为我指明了正确的方向。

为了支持文本(不仅是背景色),这是我可以正常使用的代码:

//global brushes with ordinary/selected colors
private SolidBrush reportsForegroundBrushSelected = new SolidBrush(Color.White);
private SolidBrush reportsForegroundBrush = new SolidBrush(Color.Black);
private SolidBrush reportsBackgroundBrushSelected = new SolidBrush(Color.FromKnownColor(KnownColor.Highlight));
private SolidBrush reportsBackgroundBrush1 = new SolidBrush(Color.White);
private SolidBrush reportsBackgroundBrush2 = new SolidBrush(Color.Gray);

//custom method to draw the items, don't forget to set DrawMode of the ListBox to OwnerDrawFixed
private void lbReports_DrawItem(object sender, DrawItemEventArgs e)
{
    e.DrawBackground();
    bool selected = ((e.State & DrawItemState.Selected) == DrawItemState.Selected);

    int index = e.Index;
    if (index >= 0 && index < lbReports.Items.Count)
    {
        string text = lbReports.Items[index].ToString();
        Graphics g = e.Graphics;

        //background:
        SolidBrush backgroundBrush;
        if (selected)
            backgroundBrush = reportsBackgroundBrushSelected;
        else if ((index % 2) == 0)
            backgroundBrush = reportsBackgroundBrush1;
        else
            backgroundBrush = reportsBackgroundBrush2;
        g.FillRectangle(backgroundBrush, e.Bounds);

        //text:
        SolidBrush foregroundBrush = (selected) ? reportsForegroundBrushSelected : reportsForegroundBrush;
        g.DrawString(text, e.Font, foregroundBrush, lbReports.GetItemRectangle(index).Location);
    }

    e.DrawFocusRectangle();
}

上面的代码添加到给定的代码中,将显示正确的文本并突出显示选中的项目。