开发环境:vs2010,c#窗体
要求:扩展ListBox功能,添加一方法,可以设置指定Item文字的颜色,比如:ListBox.Items[3].color = Color.Red;
通过控件扩展添加方法,可以实现,怎么做呀?vs2010listbox
要求:扩展ListBox功能,添加一方法,可以设置指定Item文字的颜色,比如:ListBox.Items[3].color = Color.Red;
通过控件扩展添加方法,可以实现,怎么做呀?vs2010listbox
调试欢乐多
public void setColor(Int index)
{
//怎么实现???
}
{
public static void Method(this ListBox listBox,Object parameter)
{
// do something
}
}
}
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();
}
}
实现
public static void ChangeColor(this ListBox listBox,int index,Color color)
{
listBox.Item[index].Color = color;
}
调用:
ListBox lBox;
// other initlize
lBox.ChangeColor(3,Color.Red);
http://www.cnblogs.com/wintalen/archive/2011/08/16/2140196.html public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
var listBox1 = new MyListBox();
listBox1.Items.Add("红色");
listBox1.Items.Add("黄色");
listBox1.Items.Add("蓝色");
listBox1.ItemColors[0] = Color.Red;
listBox1.ItemColors[1] = Color.Yellow;
listBox1.ItemColors[2] = Color.Blue;
Controls.Add(listBox1);
}
} public class MyListBox : ListBox
{
public MyListBox()
{
ItemColors = new Dictionary<int, Color>();
DrawMode = DrawMode.OwnerDrawFixed;
} public Dictionary<int, Color> ItemColors { get; private set; } protected override void OnDrawItem(DrawItemEventArgs e)
{
e.Graphics.FillRectangle(new SolidBrush(e.BackColor), e.Bounds);
var color = ItemColors.ContainsKey(e.Index) ? ItemColors[e.Index] : e.ForeColor;
e.Graphics.DrawString(Items[e.Index].ToString(), e.Font, new SolidBrush(color), e.Bounds);
e.DrawFocusRectangle();
}
}
这句有错误。