【发布时间】:2015-01-06 08:42:12
【问题描述】:
我有一个包含多个文本框和组合框的表单。我已将活动控件的背景颜色属性设置为天蓝色。我想在所有文本框和组合框不活动时将它们的背景颜色设置为白色。
【问题讨论】:
-
您的意思是不活动为不专注或启用=false?
我有一个包含多个文本框和组合框的表单。我已将活动控件的背景颜色属性设置为天蓝色。我想在所有文本框和组合框不活动时将它们的背景颜色设置为白色。
【问题讨论】:
有正确的方法和错误的方法。你在问错误的方法。正确的方法是从 TextBox 派生您自己的类并覆盖 OnEnter 和 OnLeave 方法。对 ComboBox 重复此操作。
但是您要求的方式错误,并且您可能尝试添加此功能为时已晚,因此我们必须通过在运行时找到控件来解决它。将构造函数添加到您的表单类并使其看起来像:
Public Sub New()
InitializeComponent()
FindControls(Me.Controls)
End Sub
Private Sub FindControls(ctls As Control.ControlCollection)
For Each ctl As Control In ctls
Dim match As Boolean
If TypeOf ctl Is TextBoxBase Then match = True
If TypeOf ctl Is ComboBox Then
Dim combo = DirectCast(ctl, ComboBox)
If combo.DropDownStyle <> ComboBoxStyle.DropDownList Then match = True
End If
If match Then
AddHandler ctl.Enter, AddressOf ControlEnter
AddHandler ctl.Leave, AddressOf ControlLeave
End If
FindControls(ctl.Controls)
Next
End Sub
Private controlColor As Color
Private Sub ControlEnter(sender As Object, e As EventArgs)
Dim ctl = DirectCast(sender, Control)
controlColor = ctl.BackColor
ctl.BackColor = Color.AliceBlue
End Sub
Private Sub ControlLeave(sender As Object, e As EventArgs)
Dim ctl = DirectCast(sender, Control)
ctl.BackColor = controlColor
End Sub
【讨论】:
Enter 和Leave 事件的事件处理程序还不够,而无需派生控件且没有FindControl?例如在构造函数中