使用 BorderColor 属性 创建自定义标签

create a custom label with BorderColor property

我尝试用 BorderColor 创建标签 property.but 它不起作用。我在我的表单应用程序中创建了这个标签的即时对象并尝试更改 BorderColor ,但没有任何反应。 这是我的代码:

Public Class MyLabel
Inherits Label

Private _BorderColor As Color
Dim e As New PaintEventArgs(Me.CreateGraphics, Me.DisplayRectangle)

Public Property BorderColor As Color
    Get
        Return _BorderColor
    End Get
    Set(value As Color)
        _BorderColor = value
        CreateBorder(value)
    End Set
End Property

Private Sub CreateBorder(ByVal value As Color)
    Dim g As Graphics = Me.CreateGraphics
    Dim p As Pen = New Pen(value, 2)
    g.DrawRectangle(p, Me.DisplayRectangle)
End Sub

Private Sub MyLabel_Paint(sender As Object, e As PaintEventArgs) Handles Me.Paint
    CreateBorder(_BorderColor)
End Sub

结束Class

不,不,双重不。你不要打电话给 CreateGraphicsGraphics 对象由 Paint 事件提供给您,您可以使用它。此外,您不处理自定义控件中的 Paint 事件,而是覆盖 OnPaint 方法。此外,如果您有一种绘图方法,例如CreateBorder,那么除了 OnPaint 方法之外,你不要从任何地方调用它。如果您想确保在下一个事件中重新绘制边框,那么您可以调用 Invalidate。例如

Public Class BorderedLabel
    Inherits Label

    Private _borderColor As Color

    Property BorderColor As Color
        Get
            Return _borderColor
        End Get
        Set
            _borderColor = Value
            Invalidate()
        End Set
    End Property

    Protected Overrides Sub OnPaint(e As PaintEventArgs)
        MyBase.OnPaint(e)

        Using p As New Pen(BorderColor, 2)
            e.Graphics.DrawRectangle(p, DisplayRectangle)
        End Using
    End Sub

End Class

谢谢...现在可以了 这是新代码:

Public Class MyLabel
Inherits Label

Private _BorderColor As Color
Private _BorderSize As Single = 1.0F

Public Property BorderColor As Color
    Get
        Return _BorderColor
    End Get
    Set(value As Color)
        _BorderColor = value
        Refresh()
    End Set
End Property

Public Property BorderSize As Single
    Get
        Return _BorderSize
    End Get
    Set(value As Single)
        _BorderSize = value
    End Set
End Property

Private Sub CreateBorder(ByVal value As Color, ByVal e As PaintEventArgs)
    Dim g As Graphics = e.Graphics
    Dim p As Pen = New Pen(value, _BorderSize)
    g.DrawRectangle(p, Me.DisplayRectangle)
End Sub

Private Sub MyLabel_Paint(sender As Object, e As PaintEventArgs) Handles Me.Paint
    CreateBorder(_BorderColor, e)
End Sub

结束Class