class ComboBoxEx : ComboBox
{
private ImageList imageList;
public ImageList ImageList
{
get { return imageList; }
set { imageList = value; }
}
public ComboBoxEx()
{
DrawMode = DrawMode.OwnerDrawFixed;
}
protected override void OnDrawItem(DrawItemEventArgs ea)
{
ea.DrawBackground();
ea.DrawFocusRectangle();
ComboBoxExItem item;
Size imageSize = imageList.ImageSize;
Rectangle bounds = ea.Bounds;
try
{
item = (ComboBoxExItem)Items[ea.Index];
if (item.ImageIndex != -1)
{
imageList.Draw(ea.Graphics, bounds.Left+3, bounds.Top+3,item.ImageIndex);
ea.Graphics.DrawString(item.Text, ea.Font, new SolidBrush(ea.ForeColor), bounds.Left + imageSize.Width+3, bounds.Top+3);
}
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);
}
}
class ComboBoxExItem
{
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 ComboBoxExItem()
: this(" ")
{
}
public ComboBoxExItem(string text)
: this(text, -1)
{
}
public ComboBoxExItem(string text, int imageIndex)
{
_text = text;
_imageIndex = imageIndex;
}
public override string ToString()
{
return _text;
}
}
private void Form1_Load(object sender, EventArgs e)
{
ComboBoxEx cbo = new ComboBoxEx();
cbo.ImageList = imageList1; //imageList1 设置图片12*12
cbo.Items.Add(new ComboBoxExItem("A1",0));
cbo.Items.Add(new ComboBoxExItem("A2",1));
this.Controls.Add(cbo); //放入窗体
}
自定义ComboBoxEx控件
本文介绍了一个自定义的ComboBoxEx控件,该控件扩展了标准组合框的功能,允许在其项中显示图像,并提供了相应的事件处理逻辑。通过示例展示了如何创建此类控件并将其应用于Windows窗体。
379

被折叠的 条评论
为什么被折叠?



