
| 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); } } |
| //"变形"组合框列表项类 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; } } |
| private void Form1_Load(object sender, System.EventArgs e) { //创建"变形"组合框 imageComboBox comboBox = new imageComboBox(); //设置"变形"组合框的图象列表 comboBox.ImageList = this.imageList1; //设置组合框显示风格 comboBox.DropDownStyle = ComboBoxStyle.DropDownList; //添加组合框列表项,在添加时调用OnDrawItem。 comboBox.Items.Add(new imageComboBoxItem("张伟", 0)); comboBox.Items.Add(new imageComboBoxItem("李目海", 1)); comboBox.Items.Add(new imageComboBoxItem("沙长老",0)); comboBox.Items.Add(new imageComboBoxItem("无名")); comboBox.Items.Add(new imageComboBoxItem("周纹句",1)); comboBox.Items.Add(new imageComboBoxItem("李中军",2)); comboBox.Items.Add(new imageComboBoxItem("徐文波",0)); comboBox.Items.Add(new imageComboBoxItem("少明艳",1)); comboBox.Items.Add(new imageComboBoxItem("无名军",2)); //把图象式组合框添加到表单的控件集中 this.Controls.Add(comboBox); } |
| static void Main() { //Application.Run(new Form1()); Form1 frm=new Form1(); frm.ShowDialog(); } |