c# - 列表框项的背景颜色(Windows 窗体)

标签 c# winforms listbox colors

如何设置 System.Windows.Forms.ListBox 中特定项目的背景颜色?

如果可能的话,我希望能够设置多个。

最佳答案

感谢 answer by 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();
}

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

关于c# - 列表框项的背景颜色(Windows 窗体),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/91747/

相关文章:

winforms - 我应该恢复 Clippy 吗? aka 我如何在桌面应用程序中提供用户友好的提示和帮助?

.net - 更改选定和不集中的列表框样式,使其不灰显

.net - 如何重置 .NET Windows Forms TextBox BackColor 属性?

c# - 如何使用 Microsoft Scene Understanding SDK 和 hololens2 将 Unity 场景与玩家的物理房间对齐?

c# - Blazor 始终以 UTC 格式显示日期

c# - Winform 不呈现控件更改

c# - Winforms 选项卡页面上的关闭按钮

c# - 将 JSON 文件加载到 ListBox 和 TextBox C#

python - 如何查看 Tkinter 中是否存在小部件?

c# - 在 .net core 2.2 中更新模型的正确方法,而不会通过隐藏字段出现任何安全问题