2011-08-18 29 views
0

我正在開發一個vb應用程序。在那裏我有一個列表框。我想添加不同類型的項目。像不同的彩色和不同對齊的文本(如一個項目項目右對齊,另一個左對齊)。你能告訴我,我怎麼能這樣做。如何將自定義對象添加到VB 2010的列表框中

謝謝。

+0

這樣做,你將需要繼承ListBox類和重載一些事情。在本質上,你將不得不建立你自己的基於列表框的自定義類..或去購買/找到一個.net DLL這樣做。包含列表框非常基本,只有一些全局元素的顏色可以改變。不太動態不愉快 – ppumkin

+0

其實我正在做一個聊天應用程序。當用戶輸入內容並按下輸入文字以在列表框(或任何其他控件)中顯示用戶圖像和其他信息(如時間和全部)時。有什麼辦法可以做到這一點嗎?有沒有任何控制,而不是使用ListBox? –

+0

Gridview?您可以添加列並以您想要的方式格式化它們。動態更新應用程序。我認爲比列表框好 – ppumkin

回答

1

這是我如何做它在我的項目之一(原代碼是在C#):

Public Class ColoringStepCommandListBox 
    Inherits CommandListBox 

    Const ItemHeight As Integer = 20 

    Public Sub New() 
     listBox.ItemHeight = ItemHeight 
     listBox.DrawMode = DrawMode.OwnerDrawFixed 
    End Sub 

    Protected Overrides Sub OnDrawItem(sender As Object, e As DrawItemEventArgs) 
     Const textFormatFlags__1 As TextFormatFlags = TextFormatFlags.EndEllipsis Or TextFormatFlags.PreserveGraphicsClipping Or TextFormatFlags.VerticalCenter 
     Const colorRectangleWidth As Integer = 100, textLeft As Integer = 110 

     If e.Index >= 0 Then 
      'Cast the listbox item to your custom type (ColoringStep in my example). 
      Dim coloringStep = TryCast(listBox.Items(e.Index), ColoringStep) 

      e.DrawBackground() 

      'Do custom coloring and rendering, draw icons etc. 
      Dim colorRect = New Rectangle(2, e.Bounds.Top + 2, colorRectangleWidth, ItemHeight - 5) 
      Dim innerRect = New Rectangle(colorRect.Left + 1, colorRect.Top + 1, colorRect.Width - 1, colorRect.Height - 1) 
      e.Graphics.DrawRectangle(Pens.Black, colorRect) 
      DrawingHelper.DrawGradient(coloringStep, e.Graphics, innerRect, LinearGradientMode.Horizontal) 

      'Draw the text (this does not happen automatically any more with owner draw modes). 
      Dim textRect = New Rectangle(textLeft, e.Bounds.Top, e.Bounds.Width - textLeft, e.Bounds.Height) 
      TextRenderer.DrawText(e.Graphics, coloringStep.ToString(), e.Font, textRect, e.ForeColor, textFormatFlags__1) 

      e.DrawFocusRectangle() 
     End If 
    End Sub 
End Class 
0

我得到這個簡單的解決方案。下面是代碼

Private Sub ListBox1_DrawItem(ByVal sender As Object, ByVal e As System.Windows.Forms.DrawItemEventArgs) Handles ListBox1.DrawItem 
    e.DrawBackground() 
    Dim textFont As New Font(e.Font.FontFamily, e.Font.Size * 4) 
    e.Graphics.DrawString(ListBox1.Items(e.Index).ToString(), textFont, New SolidBrush(Color.BlueViolet), RectangleF.op_Implicit(e.Bounds)) 
    e.DrawFocusRectangle() 
End Sub 

Private Sub listBox1_MeasureItem(ByVal sender As Object, ByVal e As System.Windows.Forms.MeasureItemEventArgs) Handles ListBox1.MeasureItem 
    e.ItemHeight = e.ItemHeight * 4 
End Sub 

您可以添加ListBox1_DrawItem方法中額外的代碼定製項目

相關問題