有没有人知道在WinForms C#中将图像背景插入ListBox的方法?
答案 0 :(得分:6)
好吧,你必须从ListBox继承一个新的控件。为此,在您的解决方案中创建一个“Windows Control Library”类型的新项目,并在文件控件的源代码文件中使用以下代码:
public partial class ListBoxWithBg : ListBox
{
Image image;
Brush brush, selectedBrush;
public ListBoxWithBg()
{
InitializeComponent();
this.DrawMode = DrawMode.OwnerDrawVariable;
this.DrawItem += new DrawItemEventHandler(ListBoxWithBg_DrawItem);
this.image = Image.FromFile("C:\\some-image.bmp");
this.brush = new SolidBrush(Color.Black);
this.selectedBrush = new SolidBrush(Color.White);
}
void ListBoxWithBg_DrawItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
e.DrawFocusRectangle();
/* HACK WARNING: draw the last item with the entire image at (0,0)
* to fill the whole ListBox. Really, there's many better ways to do this,
* just none quite so brief */
if (e.Index == this.Items.Count - 1)
{
e.Graphics.DrawImage(this.image, new Point(0, 0));
}
else
{
e.Graphics.DrawImage(this.image, e.Bounds, e.Bounds, GraphicsUnit.Pixel);
}
Brush drawBrush =
((e.State & DrawItemState.Selected) == DrawItemState.Selected)
? this.selectedBrush : this.brush;
e.Graphics.DrawString(this.Items[e.Index].ToString(), this.Font, drawBrush, e.Bounds);
}
}
为了简洁起见,我省略了所有设计器代码,但是您必须记住控件的Dispose
方法中的图像和画笔的Dispose
。