日期:2014-05-17  浏览次数:20392 次

C# 控件扩展,添加一方法,怎么做?
开发环境:vs2010,c#窗体
 要求:扩展ListBox功能,添加一方法,可以设置指定Item文字的颜色,比如:ListBox.Items[3].color = Color.Red;
通过控件扩展添加方法,可以实现,怎么做呀?
vs2010 listbox

------解决方案--------------------
帮你把这个链接里的方法封装了下:
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();
}
}