【发布时间】:2019-01-17 11:20:15
【问题描述】:
我创建了一个格式化条件:
- 如果文本中包含-
Success,则背景色为Green,前景色为Black; - 如果文本中包含-
Error"彩色背景Red,前景为Black; - 其他情况:背景色为
White,前景色为Black;
问题。
如何更改我选择满足条件 1 的 ListBox 项的背景/前景颜色?
条件 1。所选项目的条件:
- 后台
Color.Blue; - 前景
Color.White(或Color.Black);
问题:
我的代码没有绘制 Color.White 的 ListBox 项。
private SolidBrush reportsForegroundBrushSelected = new SolidBrush(Color.Black);
private SolidBrush reportsBackgroundBrushSelected = new SolidBrush(Color.FromKnownColor(KnownColor.Highlight));
private SolidBrush reportsForegroundBrush = new SolidBrush(Color.Black);
private SolidBrush reportsBackgroundBrush1 = new SolidBrush(Color.LimeGreen);
private SolidBrush reportsBackgroundBrush2 = new SolidBrush(Color.Salmon);
private SolidBrush reportsBackgroundBrush3 = new SolidBrush(Color.White);
private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
bool selected = ((e.State & DrawItemState.Selected) == DrawItemState.Selected);
int index = e.Index;
if (index >= 0 && index < listBox1.Items.Count)
{
string text = listBox1.Items[index].ToString();
Graphics g = e.Graphics;
//background:
SolidBrush backgroundBrush;
if (selected)
{
backgroundBrush = reportsBackgroundBrushSelected;
}
else
{
if (text.Contains("Success"))
{
backgroundBrush = reportsBackgroundBrush1;
}
else
{
backgroundBrush = reportsBackgroundBrush2;
}
}
if (!text.Contains("Success") && !text.Contains("Error"))
{
backgroundBrush = reportsBackgroundBrush3;
}
g.FillRectangle(backgroundBrush, e.Bounds);
//text:
SolidBrush foregroundBrush = (selected) ? reportsForegroundBrushSelected : reportsForegroundBrush;
g.DrawString(text, e.Font, foregroundBrush, listBox1.GetItemRectangle(index).Location);
}
e.DrawFocusRectangle();
}
【问题讨论】:
-
控件错误,使用 ListView 和 View=List。
标签: c# winforms graphics listbox gdi+