Categorize Listbox items by Color

别等时光非礼了梦想. 提交于 2019-11-29 16:59:57

A much, much better way to do this is with a ListView and an ImageList with some standard images for Text, Image, PDF etc in the list, then just set the image key for each item when you add them to the list.

Alternatively, you could emulate the same thing in a listbox (using OwnerDrawFixed) to draw a specified image to indicate the file type. A really good way to implement this is as an ExtenderProvider using code similar to that below as a starting point. As an EP, you can link any cbo or listbox to an image list to provide image cues very much like the ListView works:

The reason you do not see your colored item idiom very often is that whatever colors you pick will not look right on all systems. The more colors, the more likely and more often they wont have enough contrast, be readable etc with the user's color scheme. You also dont need a "Legend" to explain what the colors mean - an image is self explanatory. That said, the DrawItem code would be something like this:

NB: Listbox control is set to OwnerDrawFixed, ItemHeight = 16

Private Sub lb_DrawItem(sender As Object, 
           e As DrawItemEventArgs) Handles lb.DrawItem

    Dim TXT As Color = Color.Black
    Dim JPG As Color = Color.Green
    Dim PDF As Color = Color.Blue
    Dim EXE As Color = Color.Gray
    Dim SEL As Color = SystemColors.HighlightText
    Dim thisColor As Color = Color.Orange

    Dim ndx As Integer = e.Index

    ' isolate ext ans text to draw
    Dim text As String = lb.Items(ndx).ToString()
    Dim ext As String = System.IO.Path.GetExtension(text).ToLowerInvariant

    ' dont do anything if no item being drawn
    If ndx = -1 Then Exit Sub

    ' default
    e.DrawBackground()

    ' color selector
    Select Case ext
        Case ".jpg"
            thisColor = JPG
        Case ".txt"
            thisColor = TXT
        Case ".exe"
            thisColor = EXE
        Case ".pdf"
            thisColor = PDF
    End Select

    ' override color to use default when selected
    If (e.State And DrawItemState.Selected) = DrawItemState.Selected Then
        thisColor = SEL
    End If

    ' render the text
    TextRenderer.DrawText(e.Graphics, text, lb.Font, e.Bounds, 
               thisColor, TextFormatFlags.Left)

    ' default
    e.DrawFocusRectangle()

End Sub

Result:

Works on My SystemTM

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!