2011-03-17 79 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