65.9K
CodeProject 正在变化。 阅读更多。
Home

所有者绘制的 ListBox

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.71/5 (5投票s)

2008年10月31日

CPOL

1分钟阅读

viewsIcon

36460

downloadIcon

362

一个支持为每个列表项自定义绘制属性的列表框。

引言

这是一个支持使用自定义前景色绘制列表框项的列表框。可以很容易地修改以支持更多功能,但我保持了简单,并允许其他人进行探索。

列表框的绘制模式已更改为

ListBox.DrawMode = Windows.Forms.DrawMode.OwnerDrawFixed

此属性更改告诉列表框引发 DrawItem 事件。DrawItem 将负责绘制所有列表项。在这种情况下,列表框将尝试将每个列表项转换为 ICustomListBoxItemSupport 接口;如果成功,它将从接口中提取 TextColor 并使用该接口显示该值。这允许每个列表项在绘制文本时提供自己的颜色。如果转换失败,列表框仍应像现有的列表框功能一样工作。

使用 ICustomListBoxItemSupport 接口的好处是,您可以在继承自其他对象的现有对象中实现该接口,从而更容易添加到现有的业务对象中。

背景

我需要一种方法来指示某些列表项不同(或者在我的例子中,表示错误)。

使用代码

让您的列表项实现 ICustomListBoxItemSupport 接口,自定义列表框将完成剩下的工作。

Imports System.Drawing

''' <summary>
''' Example custom list box item.
''' </summary>
''' <remarks></remarks>
Public Class Person

    Implements ICustomListBoxItemSupport

    Private m_Name As String = String.Empty

    Public Property Name() As String
        Get
            Return m_Name
        End Get
        Set(ByVal value As String)
            m_Name = value
        End Set
    End Property


#Region "ICustomListBoxItemSupport implements"

    Public ReadOnly Property TextColor() As System.Drawing.Color _
           Implements ICustomListBoxItemSupport.TextColor
        Get
            If m_Name.Length > 25 Then
                Return Color.DarkRed
            Else
                Return SystemColors.WindowText
            End If
        End Get
    End Property

    Public Property DisplayValue() As String _
           Implements ICustomListBoxItemSupport.DisplayValue
        Get
            Return Me.Name
        End Get
        Set(ByVal value As String)

        End Set
    End Property

#End Region

End Class
© . All rights reserved.