题目要求是在c#中的combobox控件的下拉列表中添加图片。我有代码,可是有错误,图片添加部分不

2025-05-07 19:13:24
推荐回答(3个)
回答1:

class PicComboBox : System.Windows.Forms.ComboBox
{
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);
}

///


/// 内部类,用于添加图片文本项
///


public class PicItem
{
public PicItem(Image img, string text)
{
Text = text;
Image = img;
}

public string Text { get; set; }
public Image Image { get; set; }

public override string ToString()
{
return Text;
}
}
}
这是一个完整的可以添加图片的combox类,用法:
PicComboBox PCB = new PicComboBox();
PCB.Items.Add(new PicComboBox .PicItem(这里是图片,这里是文本)
其中文本可以为空
这是我自己写的、如果觉得外观不好看什么的可以自己修改上面的代码

回答2:

直接在后台combobox的item的项定义时指向图片路径

回答3:

用imagelist不可以吗