问题描述
我有一些代码可以改变列表框的行为方式.我可以更改文本的颜色,但我无法更改每行的背景颜色.
I have some code to change how listbox act. I can change the color of text, but I am unable to change the color of the background of each line.
我的每一行都在 for 循环中
This is in a for loop for every of my lines
LBLines 是一个存储在全局变量中的字符串数组
LBLines is an array of string store in a global variable
if (LBLines[e.Index] != "None")
{
e.Graphics.FillRectangle(new SolidBrush(Color.FromName(LBLines[e.Index])),
e.Bounds.X,e.Bounds.Y,e.Bounds.Width,e.Bounds.Height);
}
这将为每条线着色相同颜色,即使是那些列为无"的线,我需要的是它们保持与默认背景颜色相同的颜色.
This will color EVERY lines of the same color, even those listed as "None", thou what I need is that they stay same color as default background color.
比较不是问题,问题来自 e.Graphics.FillRectangle.不管我画的是什么,它似乎都给所有的线条空间着色.
Comparaison is not the problem, problem come from the e.Graphics.FillRectangle. It seems to color ALL the lines spaces, regardless of the one I am drawing.
修改代码以显示 h 等于 e.Index
Modified code to show that h was equal to e.Index
推荐答案
如果没有更多关于代码(循环、方法等)的上下文,很难说,但是这段代码可以满足我的需求:
Hard to say without more context around your code (the loop, the method,...), but this code does what I think it is you want:
public partial class Form1 : Form
{
string[] Colors { get; set; }
public Form1()
{
InitializeComponent();
Colors = new string[] { "red", "blue", "white", "none", "orange" };
listBox1.Items.AddRange(Colors);
}
private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
if (Colors[e.Index] != "none")
{
using (var brush = new SolidBrush(Color.FromName(Colors[e.Index])))
{
e.Graphics.FillRectangle(brush, e.Bounds);
}
}
e.Graphics.DrawString(Colors[e.Index], Font, SystemBrushes.ControlText, e.Bounds);
}
}
注意 ListBox
的 DrawStyle
属性设置为 OwnerDrawFixed
.
Note that the DrawStyle
property of the ListBox
is set to OwnerDrawFixed
.
这篇关于C# Listbox.DrawItem 为每一行着色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!