gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 03:51:35 26 4
gpt4 key购买 nike

如何设置 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com