2011-03-17 77 views
0

添加图标列表框中vb.net

我如何通过左侧绘制图像中listbox_DrawItem事件

我已经读过throught this code,它的击打不是帮我

Dim targetsize As New Size(16, 16) 
Dim img As Image = Nothing 
img = My.Resources._error 
e.Graphics.DrawImage(img, targetsize) 
e.Graphics.DrawString(lsbLog.Items(e.Index).ToString(), _ 
           e.Font, mybrush, e.Bounds, StringFormat.GenericDefault) 

这是我现在的代码

编辑

我添加了你的c颂与其他一些代码,我得到一个乱码

这是DrawItem事件的部分代码

'//Here it draws the border depeding on it's state (the listbox item) 
     e.Graphics.DrawRectangle(myPen, e.Bounds.X + 16, e.Bounds.Y, _ 
           e.Bounds.Width - 16, e.Bounds.Height) 
     Using b As New SolidBrush(e.ForeColor) 
      e.Graphics.DrawString(lsbLog.GetItemText(lsbLog.Items(e.Index)), e.Font, b, e.Bounds) 
     End Using 
     e.Graphics.DrawImage(img, New Rectangle(e.Bounds.Width - 15, e.Bounds.Y, 12, 12)) 
     '// Draw the current item text based on the current 
     '// Font and the custom brush settings. 
     e.Graphics.DrawString(lsbLog.Items(e.Index).ToString(), e.Font, mybrush, _ 
           New Rectangle(e.Bounds.X - 20, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height), _ 
           StringFormat.GenericDefault) 

这是MeasureItem事件

Private Sub lsbLog_MeasureItem(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MeasureItemEventArgs) Handles lsbLog.MeasureItem 
     Dim g As Graphics = e.Graphics 
     'We will get the size of the string which we are about to draw, 
     'so that we could set the ItemHeight and ItemWidth property 
     Dim size As SizeF = g.MeasureString(lsbLog.Items.Item(e.Index).ToString, Me.Font, _ 
     lsbLog.Width - (5 + SystemInformation.VerticalScrollBarWidth)) 
     e.ItemHeight = CInt(size.Height) + 5 
     e.ItemWidth = CInt(size.Width) + 5 
    End Sub 

代码我得到一个加标签的文字和图像

I get a garbled image

+0

您检查了这是否有帮助吗? http://www.codeproject.com/KB/combobox/glistbox.aspx – 2011-03-17 12:03:22

+0

@Simen人对这篇文章评论为非常差,并且bug填充 – Smith 2011-03-17 12:28:03

+0

你想达到什么目的?如果你想让图像左对齐,为什么使用'Width - 15'作为X坐标?你应该在这里使用'e.Bounds.X'。为什么你在列表框的外部开始文本*(即你把X设置为'e.Bounds.X - 20')?不应该是'e.Bounds.X + 20'吗? – Heinzi 2011-03-17 14:56:54

回答

1

两点来到了我的注意:

  • 你设置DrawModeDrawMode.OwnerDrawFixedDrawMode.OwnerDrawVariable,如stated in the documentation

  • 您似乎是直接在图像上绘制文本。为什么在DrawString中使用e.Bounds而不是一个向右开始的矩形?例如。是这样的:

    Dim rect As New Rectangle(e.Bounds.X + 16, e.Bounds.Y, _ 
              e.Bounds.Width - 16, e.Bounds.Height) 
    ' use rect instead of e.Bounds in DrawString 
    

顺便说一句,你不应该忘记调用DrawBackgroundDrawFocusRectange作为例子in the documentation看到。

+0

是的,我将drawmode设置为'DrawMode.OwnerDrawVariable'。你可以给我替代'e.bounds' – Smith 2011-03-17 12:06:32

+0

@史密斯:我会使用OwnerDrawFixed,因为你不改变项目的高度。我已经添加了一个关于如何调整字符串的矩形边界的示例。顺便说一句,作为调试的提示:它是否正确绘制图像,如果你只是注释掉DrawString语句? – Heinzi 2011-03-17 12:14:15

+0

我确实改变了物品的高度,请检查我的代码 – Smith 2011-03-17 12:28:49