如何将自定义对象添加到VB 2010的列表框中

时间:2011-08-18 09:39:52

标签: vb.net

我正在开发一个vb应用程序。在那我有一个列表框。我想添加不同类型的项目。像不同颜色和不同对齐的文本(像一个项目项目是右对齐,还有一个是左对齐)。你能告诉我我怎么能这样做。

感谢。

1 个答案:

答案 0 :(得分: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