首页 > 其他 > 详细

带图标和自定义颜色的ListBox

时间:2014-04-21 11:27:21      阅读:498      评论:0      收藏:0      [点我收藏+]

自定义控件的实现

--------带图标和自定义颜色的ListBox

在一个点对点文件传输的项目中,我需要显示文件传输的实时信息:传输的文件列表和当前传输的文件,当时我想到了用ListBox,但是但我用了ListBox后,我发现它不能改变控件中文本想的颜色,于是我就想扩展一下ListBox控件------ListBoxEx。

我的目标是给空间加上图标,还要能时时改变控件文本颜色。于是从ListBox派生类

public class ListBoxEx : ListBox {…}

为了操作方便我为ListBoxEx的每一项设计专门的类ListBoxExItem

public class ListBoxExItem {…}

为了保持我这个控件与WinForm的标准控件的操作借口一致,我又重新设计了两个集合类

public class ListBoxExItemCollection : IList, ICollection, IEnumerator {}//这个类相对于标准ListBox中的ObjectCollection,这个类作为ListBoxEx中的Items属性的类型

public class SelectedListBoxExItemCollection : : IList, ICollection, IEnumerator{}//这个类相对于标准ListBox中的SelectedObjectCollection,这个类作为ListBoxEx中的SelectedItems属性的类型

下面看两个集合类的实现:

ListBoxExItemCollection的实现:为了做到对集合(Items)的操作能够及时反映到ListBoxEx的控件中所以,此类只是对ListBox中Items(ObjectCollection类型)作了一层包装,就是把ListBox中Items属性的所有方法的只要是object类型的参数都转换成ListBoxExItem,比如:

public void Remove(ListBoxExItem item)

{

this._Items.Remove(item); //_Items为ObjectCollection类型

}

public void Insert(int index, ListBoxExItem item)

{

this._Items.Insert(index, item);

}

public int Add(ListBoxExItem item)

{

return this._Items.Add(item);

}

由上可知,ListBoxExItemCollection中有一个构造函数来传递ListBox中的Items对象

private ObjectCollection _Items;

public ListBoxExItemCollection(ObjectCollection baseItems)

{

this._Items = baseItems;

}

而SelectedListBoxExItemCollection类的实现也用同样的方法,只不过是对SelectedObjectCollection包装罢了。

集合实现后,再来看ListBoxExItem的实现:

为了使它支持图标和多种颜色添加如下成员

private int _ImageIndex;

public int ImageIndex

{

get { return this._ImageIndex; }

set { this._ImageIndex = value;}

}

private Color _ForeColor;

public Color ForeColor

{

get{ return this._ForeColor;}

set

{

this._ForeColor = value;

this.Parent.Invalidate();

}

}

当然还有

private string _Text;

public string Text

{

get { return this._Text; }

set { this._Text = value; }

}

为了控件能正确显示此项的文本,还必须重写ToString()方法

public override string ToString()

{

return this._Text;

}

带图标和自定义颜色的ListBox,布布扣,bubuko.com

带图标和自定义颜色的ListBox

原文:http://blog.csdn.net/u014440209/article/details/24234285

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!