vb.net中的按钮类

问题描述 投票:0回答:1

我正在尝试通过继承button属性来为按钮控件创建一个类。我想通过创建新的按钮类在默认属性中添加更多属性

最初,新属性将为:1)底部和顶部颜色2)圆角

请参见下面的代码

'下面是我尝试过的代码

 Class MyButton
    Inherits Button

    Public Property TopColor As Color
    Public Property BottomColor As Color

    Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs)
        Dim lgb As LinearGradientBrush = New 
          LinearGradientBrush(Me.ClientRectangle, Me.TopColor, 
          Me.BottomColor, 90.0F)
        Dim g As Graphics = e.Graphics
        g.FillRectangle(lgb, Me.ClientRectangle)
        MyBase.OnPaint(e)
    End Sub
End Class

当我为顶部和底部颜色分配颜色时,底部的颜色没有改变。即使我也没有收到任何错误消息

vb.net visual-studio vb.net-2010
1个回答
0
投票

您只需要使用属性设置器(当然还有Getter),因此可以在更改属性值时调用Invalidate()。这将引发Paint事件,导致控件重新绘制自身。OnPaint方法中的代码将使用新的颜色重新绘制Button的图形。

您还需要绘制按钮的文本,因为在绘制按钮的内容时它会被删除。这也意味着我们认为TextAlign属性可以将Text重新绘制到正确的位置。我在这里使用StrinFormat来对齐由Button的TextAlign属性定义的文本。请参见GetVerticalAlignment()GetHorizontalAlignment()方法。

最后但并非最不重要的是,必须丢弃背景画笔和前景画笔,以避免泄漏图形资源。 StringFormat对象也是如此。我们只需要使用Using语句声明这些对象,然后在Using块内使用它们。当我们完成对这些对象的处理后,将负责处理这些对象。

Imports System.Drawing.Drawing2D
Imports System.Windows.Forms

Class MyButton
    Inherits Button

    Private m_TopColor As Color = Color.LightGreen
    Private m_BottomColor As Color = Color.Orange

    Public Property TopColor As Color
        Get
            Return m_TopColor
        End Get
        Set(ByVal value As Color)
            m_TopColor = value
            Me.Invalidate()
        End Set
    End Property

    Public Property BottomColor As Color
        Get
            Return m_BottomColor
        End Get
        Set(ByVal value As Color)
            m_BottomColor = value
            Me.Invalidate()
        End Set
    End Property

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

        Using lgb As LinearGradientBrush = New LinearGradientBrush(Me.ClientRectangle, m_TopColor, m_BottomColor, 90.0F)
            Using textBrush As SolidBrush = New SolidBrush(Me.ForeColor)
                Using format As StringFormat = New StringFormat()
                    format.Alignment = GetHorizontalAlignment()
                    format.LineAlignment = GetVerticalAlignment()
                    e.Graphics.FillRectangle(lgb, Me.ClientRectangle)
                    e.Graphics.DrawString(Me.Text, Me.Font, textBrush, Me.ClientRectangle, format)
                End Using
            End Using
        End Using
    End Sub

    Private Function GetVerticalAlignment() As StringAlignment
        Return CType(Math.Log(Me.TextAlign, 2D) / 4, StringAlignment)
    End Function

    Private Function GetHorizontalAlignment() As StringAlignment
        Return CType(Math.Log(Me.TextAlign, 2D) Mod 4, StringAlignment)
    End Function

End Class
© www.soinside.com 2019 - 2024. All rights reserved.