这是我的代码,应该改变我的任何按钮的背面颜色,但它不起作用,我不知道什么是错的:
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
答案 0 :(得分:1)
System.Drawing.Color
是值类型(结构)。当您将其传递给color
方法时,只会传递一个副本,并且您的方法只会更改副本。您应该将Sub更改为Function并返回颜色并将其指定给按钮的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
Per @ VisualVincent的评论,你可以在你的Sub:
中使用ByRef
Private Sub ChangeColor(ByRef c As System.Drawing.Color)
c = Color.CadetBlue
End Sub
答案 1 :(得分:1)
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
适用于任何控件(Textboxes,Labels e.t.c)
答案 2 :(得分:1)
您可以创建一个扩展方法来执行此操作。创建公共模块,如下所示:
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()