[英]C# Color of listbox item continued
I'm trying to find a way to highlight the background of list box items with different colors, and came across this four year old closed thread that almost answers the question here: 我试图找到一种方法来突出显示具有不同颜色的列表框项目的背景,并且遇到了这个已有四年历史的封闭线程,几乎可以在这里回答问题:
Background color of a ListBox item (winforms) ListBox项的背景色(winforms)
I'm not following how to use his method. 我没有遵循如何使用他的方法。 So if I created an object named listBox1 and a string variable named strSomeString, what would be the exact code for adding strSomeString to listBox1 with a red background?
因此,如果我创建了一个名为listBox1的对象和一个名为strSomeString的字符串变量,将strSomeString添加到具有红色背景的listBox1的确切代码是什么?
Using Shadow Wizard's code here: 在此处使用Shadow Wizard的代码:
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;
Color color = (selected) ? Color.FromKnownColor(KnownColor.Highlight) : (((index % 2) == 0) ? Color.White : Color.Gray);
g.FillRectangle(new SolidBrush(color), e.Bounds);
// Print text
g.DrawString(text, e.Font, (selected) ? reportsForegroundBrushSelected : reportsForegroundBrush,
lbReports.GetItemRectangle(index).Location);
}
e.DrawFocusRectangle();
}
-Thanks -谢谢
Consider using an owner draw control for this. 考虑为此使用所有者绘制控件 。
It's more work because you need to render all the list contents. 这需要更多工作,因为您需要呈现所有列表内容。 But you'll have total flexibility.
但是您将拥有完全的灵活性。
You just need to hook the Draw_item event of the listbox to lbReports_DrawItem handler. 您只需要将列表框的Draw_item事件挂接到lbReports_DrawItem处理程序即可。 You can do that by set it at the properties of the listbox.
您可以在列表框的属性中进行设置。
Another thing is to Set the DrawMode to OwnerDrawFixed 另一件事是将DrawMode设置为OwnerDrawFixed
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.