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

解决方案 »

  1.   

    写个控件继承ListBox,添加一个方法
      

  2.   

    知道这样做,具体怎么实现?
    public void setColor(Int index)
    {
        //怎么实现???
    }
      

  3.   

    可以从ListBox继承一个新类,也可以试试扩展方法,使用方法如下:public static class ListBoxExention
    {
    public static void Method(this ListBox listBox,Object parameter)
    {
        // do something
    }
    }
    }
      

  4.   

    // do something 关键是如何实现呀???
      

  5.   


     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();
                }
            }
      

  6.   

    // do something 关键是如何实现呀???
    实现
    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);
      

  7.   

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

  8.   

    listBox.Item[index].Color = color;  这一句实现不了。
      

  9.   

    e.Graphics.DrawString(Items[e.Index].ToString(), e.Font, new SolidBrush(color), e.Bounds);
    这句有错误。