科技行者

行者学院 转型私董会 科技行者专题报道 网红大战科技行者

知识库

知识库 安全导航

至顶网软件频道基础软件Visual C#组件技巧之深入ComboBox美容

Visual C#组件技巧之深入ComboBox美容

  • 扫一扫
    分享文章到微信

  • 扫一扫
    关注官方公众号
    至顶头条

在上一篇文章中我们谈到了如何用编程的方式实现ComboBox美容,使普通的ComboBox控件变得多姿多彩

作者:张伟 来源:yesky 2007年11月14日

关键字: Visual C# 组件 ComboBox 美容

  • 评论
  • 分享微博
  • 分享邮件
一、问题的提出

  在上一篇文章中我们谈到了如何用编程的方式实现ComboBox美容,使普通的ComboBox控件变得多姿多彩(如字体的变大、颜色的变化以及中上图像),但是这种变化是有一定的局限性:即强烈的顺序感。本文就来解决"强烈的顺序感"的问题,这种做法是很有必要的。

  例如在一个ComboBox中显示的全体2001级计算机系优秀学生干部,为了明确地区分某个学生是属性某一个年级,我们可采用在每个学生面前放置图标的方法,如一年级的学生面前放置 ,二年级的学生前面放置 ,三年级的学生面前放置 ,不知年级的学生前面不放置任何图标等来区分,如图1所示。


图1

  在图1中可以看出"没有强烈的顺序感",弥补了上一篇文章的不足之处。这到底是如何实现的呢?

  二、解决方法分析

  从图1可以看出,我们所用的组合框只是在标准组合框的基础上进行了修改(添加图像列表)而形成的,因此读者很容易想到C#中自定义控件的方法之一:继承原有控件的方法。本文中的"变形组合框"就是在标准的ComboBox继承得到的,在标准的ComboBox基础上添加了一个图像列表,其代码如下:

public class imageComboBox : System.Windows.Forms.ComboBox//继承ComboBox
{
//添加ImageList型的变量来保存ImageList属性的值
private ImageList _imageList;
//定义ImageList属性
public ImageList ImageList
{
get
{
return _imageList;
}
set
{
_imageList = value;
}
}
/*设置绘画方式为OwnerDrawFixed,这一步很关键*/
public imageComboBox()
{
DrawMode = DrawMode.OwnerDrawFixed;
}

//重载OnDrawItem函数,来绘制组合框中每一列表项
protected override void OnDrawItem(DrawItemEventArgs ea)
{
ea.DrawBackground();
ea.DrawFocusRectangle();

imageComboBoxItem item;
Size imageSize = _imageList.ImageSize;
Rectangle bounds = ea.Bounds;

try
{
/*关于imageComboBoxItem的定义在下面论述*,这一步也是关键/
item = (imageComboBoxItem)Items[ea.Index];
/*在此处用了一个小技巧。因为组合框列表项中的索引从0开始,对于那些没有图标的项(用于不知道属性哪一个年级的学生)把其索引设置为-1,即只要其索引值不为-1,表明有图像;否则没有图像*/
if (item.ImageIndex != -1)//即有图像又有文本
{
//画图像
_imageList.Draw(ea.Graphics, bounds.Left, bounds.Top, item.ImageIndex);
//绘制文本
ea.Graphics.DrawString(item.Text, ea.Font, new
SolidBrush(ea.ForeColor), bounds.Left+imageSize.Width, bounds.Top);
}
else//只有文本,没有图像
{
  //写文本
ea.Graphics.DrawString(item.Text, ea.Font, new
SolidBrush(ea.ForeColor), bounds.Left, bounds.Top);
}
}
//一定要有
catch
{
if (ea.Index != -1)
{
ea.Graphics.DrawString(Items[ea.Index].ToString(), ea.Font, new
SolidBrush(ea.ForeColor), bounds.Left, bounds.Top);
}
else
{
ea.Graphics.DrawString(Text, ea.Font, new
SolidBrush(ea.ForeColor), bounds.Left, bounds.Top);
}
}

base.OnDrawItem(ea);
}
}

  再仔细观察图1,发现"变形"组合框中列表项与普通组合框中列表项中有所不同(多了图像),在此我们定义一个类来描述"变形"组合框列表项,其代码如下:

//"变形"组合框列表项类
public class imageComboBoxItem
{
//定义文本属性
private string _text;
public string Text
{
get {return _text;}
set {_text = value;}
}
//定义图象索引属性
private int _imageIndex;
public int ImageIndex
{
get {return _imageIndex;}
set {_imageIndex = value;}
}
//初始化函数之一:即没有图象也没有文本
public imageComboBoxItem():this("",-1)
{
}
//初始化函数之二:没有图象,只有文本(针对不知属性哪一年级学生)
public imageComboBoxItem(string text): this(text, -1)
{
}
//初始化函数之三:文本与图象都有
public imageComboBoxItem(string text, int imageIndex)
{
_text = text;
_imageIndex = imageIndex;
}

public override string ToString()
{
return _text;
}
}
    • 评论
    • 分享微博
    • 分享邮件
    邮件订阅

    如果您非常迫切的想了解IT领域最新产品与技术信息,那么订阅至顶网技术邮件将是您的最佳途径之一。

    重磅专题
    往期文章
    最新文章