扫一扫
分享文章到微信
扫一扫
关注官方公众号
至顶头条
图1 |
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; } } |
如果您非常迫切的想了解IT领域最新产品与技术信息,那么订阅至顶网技术邮件将是您的最佳途径之一。
现场直击|2021世界人工智能大会
直击5G创新地带,就在2021MWC上海
5G已至 转型当时——服务提供商如何把握转型的绝佳时机
寻找自己的Flag
华为开发者大会2020(Cloud)- 科技行者