我有代码,该代码突出显示了当前的文本框,以便为用户提供视觉提示。我的问题是,如果我有10个带有文本框的表格,并且我想向所有人提供相同的代码。我是否必须复制它,还是可以使用全局方法?如果是这样,一个例子将非常有帮助。谢谢。
代码如下。
Private Sub FocusChanged(ByVal sender As Object, ByVal e As EventArgs)
Dim txt As TextBox = sender
If txt.Focused Then
txt.Tag = txt.BackColor
txt.BackColor = Color.AliceBlue
Else
txt.BackColor = txt.Tag
End If
End Sub
Private Sub CreateAccount_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
For Each ctrl As TextBox In Me.Controls.OfType(Of TextBox)()
AddHandler ctrl.GotFocus, AddressOf FocusChanged
AddHandler ctrl.LostFocus, AddressOf FocusChanged
ctrl.Tag = ctrl.BackColor
Next
End Sub
如果要将此行为添加到所有文本框控件中,则最好是从文本框类中派生自己的类,并覆盖OnGotFocus
和OnLostFocus
方法相应地设置属性。
这是:
Public Class MyTextBox
Inherits TextBox
Protected Overrides Sub OnGotFocus(e As System.EventArgs)
MyBase.OnGotFocus(e)
Me.Tag = Me.BackColor
Me.BackColor = Color.Aqua
End Sub
Protected Overrides Sub OnLostFocus(e As System.EventArgs)
MyBase.OnLostFocus(e)
Me.BackColor = Me.Tag
End Sub
End Class
编辑:忘了提到在项目中添加该类后,重建解决方案,如果没有错误编译,则您的新TextBox类显示在VS工具箱中显示。然后,您可以简单地拖动&像任何控件一样落在您的表格上。
欢呼