如何在formload drawitem上调用事件

How to call event on formload drawitem

我正在使用此代码将图像放入列表框中,但文本不显示。当我单击列表时,它会显示 .有什么问题?

form_load()
{
   listbox1.Items.Add("string");
   listbox1.DrawMode = DrawMode.OwnerDrawVariable;
}

private void listbox1_DrawItem(object sender, DrawItemEventArgs e)
{
   ListBox lst = sender as ListBox;
   e.Graphics.DrawImage(imageList1.Images[0], 0, 0, 10, 10);
   e.Graphics.DrawString(lst.Text, this.Font,SystemBrushes.ControlDark, 11, 0);
}

嗯,看起来你画的东西不对。 DrawItem 正在为列表框中的每个项目调用事件,但您一直在同一位置绘制相同的文本。您应该使用 e.Bounds 来确定每个项目的位置。如果您需要一些非标准尺寸,您还可以处理 MeasureItem 事件为每个项目设置自定义边界。

另外lst.Text在这里意义不大,应该是当前要绘制的item的文字,基于e.Index.

因此,您的代码绘制字符串的一部分可能类似于:

e.Graphics.DrawString(lst.GetItemText(lst.Items[e.Index]), 
                      this.Font, SystemBrushes.ControlDark, e.Bounds.Left, e.Bounds.Top);

您还可以在 MSDN 上找到一些有用的 example