winform设计时 怎么在下拉框中添加图片呢?请知道的人帮一下忙哈!

 我来答
maoxiaoling959
2011-10-22 · 超过39用户采纳过TA的回答
知道小有建树答主
回答量:78
采纳率:0%
帮助的人:98.1万
展开全部
ComboBox With Images
By Rakka Rage

There is no built in support for a ComboBox with images. So i created a simple ComboBoxEx class that derives from ComboBox and allows you to set the ComboBoxEx.ImageList property and ComboBoxExItem.ImageIndex property so that the ComboBox displays an image.

...
ComboBoxEx comboBox = new ComboBoxEx();
comboBox.ImageList = imageList;
// not needed but... no icon for index -1 else
comboBox.DropDownStyle = ComboBoxStyle.DropDownList;
// just pass these in instead of strings, class included below
// specify a valid imageIndex
comboBox.Items.Add(new ComboBoxExItem( "Text0 ", 0));
comboBox.Items.Add(new ComboBoxExItem( "Text1 ", 1));

Code:
namespace Rage.Library
{
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, 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);
}
}

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;
}
}
}
追问
请问这是做组件吗?我是初学者,可以说的详细些么?谢谢啦!
追答
不是组件,新建一个类 class   ComboBoxEx   :   ComboBox,看这里,继承ComboBox,然后在ComboBoxEx   封装 ComboBox的一些属性值。  protected   override   void   OnDrawItem这个方法是重绘ComboBox的下拉选择框。具体效果需要你耐心 的去测试一下!测试成功了说明你懂了,光把代码帖上去也没多大意思
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式