{
public PicComboBox()
{
//默认值设置
DrawMode = DrawMode.OwnerDrawFixed
DropDownStyle = ComboBoxStyle.DropDownList
ItemHeight = 50
Width = 200
}
protected override void OnDrawItem(DrawItemEventArgs e)
{
if (Items.Count == 0 || e.Index == -1) return
if ((e.State &DrawItemState.Selected) != 0)
{
//选中项背景
LinearGradientBrush brush = new LinearGradientBrush(e.Bounds, Color.FromArgb(255, 251, 237), Color.FromArgb(255, 236, 181), LinearGradientMode.Vertical)
//LinearGradientBrush brush = new LinearGradientBrush(e.Bounds, Color.Red , Color.Blue , LinearGradientMode.Vertical)
Rectangle borderRect = new Rectangle(0, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height)
e.Graphics.FillRectangle(brush, borderRect)
Pen pen = new Pen(Color.FromArgb(229, 195, 101))
e.Graphics.DrawRectangle(pen, borderRect)
}
else
{
SolidBrush brush = new SolidBrush(Color.FromArgb(255, 255, 255))
e.Graphics.FillRectangle(brush, e.Bounds)
}
//绘制图片
PicItem item = (PicItem)Items[e.Index]
Image img = item.Image
double newwidth = Convert.ToDouble(ItemHeight - 3) * img.Width / img.Height//保持图片高宽比不变,并先满足高度
Rectangle imgRect = new Rectangle(2, e.Bounds.Y + 2, Convert.ToInt16(newwidth), e.Bounds.Height - 3)
e.Graphics.DrawImage(img, imgRect)
//绘制文本
Rectangle textRect = new Rectangle(imgRect.Right + 2, imgRect.Y, e.Bounds.Width - imgRect.Width, e.Bounds.Height - 3)
String itemText = Items[e.Index].ToString()
StringFormat strFormat = new StringFormat()
strFormat.LineAlignment = StringAlignment.Center
e.Graphics.DrawString(itemText, Font, new SolidBrush(ForeColor), textRect, strFormat)
base.OnDrawItem(e)
}
/// <summary>
/// 内部类,用于添加图片文本项
/// </summary>
public class PicItem
{
public PicItem(Image img, string text)
{
Text = text
Image = img
}
public string Text { getset}
public Image Image { getset}
public override string ToString()
{
return Text
}
}
}
这是一个完整的可以添加图片的combox类,用法:
PicComboBox PCB = new PicComboBox()
PCB.Items.Add(new PicComboBox .PicItem(这里是图片,这里是文本)
其中文本可以为空
这是我自己写的、如果觉得外观不好看什么的可以自己修改上面的代码
toolstripcombobox.combobox 这样可以获得toolstripcombobox的原始combobox
得到这个就是一个标准的combobox了
就可以重写DrawItem事件,就可以添加图片了
为Combox添加选项有几个方法
1、窗体设计时
在属性窗口中找到List属性,直接添加即可,如下图:
2、通过代码添加
Combo1.AddItem "内容"
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)