无法通过自定义方法更改按钮的背景颜色

Cannot change the back color of a button via a custom method

这是我的代码,可以更改任何按钮的背景颜色,但它不起作用,我也不知道出了什么问题:

Public Sub color(ByVal backcolor As System.Drawing.Color)
    backcolor = Drawing.Color.CadetBlue
End Sub

这是我在单击按钮时调用它的方式。它应该改变 Button1 的背景颜色,但它没有。我做得对还是我漏掉了什么?

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    color(Button1.BackColor)
End Sub

System.Drawing.Color是一个值类型(结构)。当您将它传递给 color 方法时,只会传递一个副本,而您的方法只会更改该副本。您应该将 Sub 更改为函数和 return 颜色并将其分配给按钮的 BackColor 属性:

Public Function color() As System.Drawing.Color
    Return System.Drawing.Color.CadetBlue
End Function

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Button1.BackColor = color()
End Sub

尽管该功能没有增加任何价值。您可能应该直接设置颜色:

Button1.BackColor = System.Drawing.Color.CadetBlue

根据@VisualVincent 的评论,您可以在您的 Sub:

中使用 ByRef
Private Sub ChangeColor(ByRef c As System.Drawing.Color)
    c = Color.CadetBlue
End Sub
Public Sub color(ByVal btn As Control, ByVal clr As System.Drawing.Color)
    btn.BackColor = clr
End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    color(Button1, Drawing.Color.CadetBlue)
End Sub

或者

Public Sub color(ByVal btn As Control)
    btn.BackColor = Drawing.Color.CadetBlue
End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    color(Button1)
End Sub

适用于任何控件(文本框、标签 e.t.c)

您可以创建一个扩展方法来执行此操作。创建一个public模块如下:

Public Module Module1    
    <Runtime.CompilerServices.Extension()>
    Public Sub SetBackColourToCadetBlue(aButton As Button)
    'Use the following line for Telerik Button
    'Public Sub SetBackColourToCadetBlue(aButton As Telerik.WinControls.UI.RadButton) 
        aButton.BackColor = Color.CadetBlue
    End Sub
End Module

您可以调用以下命令来设置任何按钮的背景颜色:

Button1.SetBackColourToCadetBlue()