改变Listbox中的字体颜色

  • Post author:
  • Post category:其他


当用ListBox来作输出显示的时候,有时需要针对不同的输出显示不同的颜色,比如当用ListBox来作告警输出的时候,需要根据不同的告警等级来显示不同的颜色,以达到醒目的作用,其实用ListBox来做这种事情很容易。

首先把ListBox的DrawMode设为OwnerDrawFixed或是OwnerDrawVariable,然后在ListBox的DrawItem事件中加入下面的代码


private void listBox_DrawItem(object sender, DrawItemEventArgs e)
{
Brush FontBrush = null;
ListBox listBox = sender as ListBox;
if (e.Index > -1)
{
switch (listBox.Items[e.Index].ToString())
{
case "Critical": FontBrush = Brushes.Brown; break;
case "Major": FontBrush = Brushes.Red; break;
case "Minor": FontBrush = Brushes.Orange; break;
case "Warning": FontBrush = Brushes.Yellow; break;
default: FontBrush = Brushes.Black; break;
}
e.DrawBackground();
e.Graphics.DrawString(listBox.Items[e.Index].ToString(), e.Font, FontBrush, e.Bounds);
e.DrawFocusRectangle();
}
}

即可。

完整的程序代码如下:以下代码在vs2005中测试通过


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace ListBoxDataGrid
{
public partial class ListBoxForm : Form
{
public ListBoxForm()
{
InitializeComponent();
}
private void listBox_DrawItem(object sender, DrawItemEventArgs e)
{
Brush FontBrush = null;
ListBox listBox = sender as ListBox;
if (e.Index > -1)
{
switch (listBox.Items[e.Index].ToString())
{
case "Critical": FontBrush = Brushes.Brown; break;
case "Major": FontBrush = Brushes.Red; break;
case "Minor": FontBrush = Brushes.Orange; break;
case "Warning": FontBrush = Brushes.Yellow; break;
default: FontBrush = Brushes.Black; break;
}
e.DrawBackground();
e.Graphics.DrawString(listBox.Items[e.Index].ToString(), e.Font, FontBrush, e.Bounds);
e.DrawFocusRectangle();
}
}
private void button_Click(object sender, EventArgs e)
{
if (!textBox.Text.Length.Equals(0))
listBox.Items.Add(textBox.Text);
}
}
}

转自:http://www.cnblogs.com/aaliujing/archive/2007/01/29/633689.html



版权声明:本文为liaoxueli原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。