Vb.Net - 动态更改文本框背景色的类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16134227/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Vb.Net - Class to Change Textbox BackColor Dynamically
提问by APS
I'd like to know how to create a Class to change each textbox BackColor inside a Form. To be more Specific:
我想知道如何创建一个类来更改表单中的每个文本框 BackColor。更具体:
- When the textbox Is Empty, the textbox BackColor equals White.
- When the textbox Get focus, the textbox BackColor change.
- When the textbox have any text, the textbox BackColor change.
- When the textbox Lost focus, the textbox BackColor change.
- 当文本框为空时,文本框 BackColor 等于 White。
- 当文本框获得焦点时,文本框的 BackColor 发生变化。
- 当文本框有任何文本时,文本框的 BackColor 会发生变化。
- 当文本框失去焦点时,文本框的背景色发生变化。
At the moment, I'm doing it this way.
目前,我正在这样做。
Private Sub tb_Login_Enter(sender As Object, e As EventArgs) Handles tb_Login.Enter
tb_Login.BackColor = Color.LightCyan
End Sub
Private Sub tb_Login_Leave(sender As Object, e As EventArgs) Handles tb_Login.Leave
If tb_Login.Text <> "" Then
tb_Login.BackColor = Color.LightGreen
Else
tb_Login.BackColor = Color.White
End If
But, I have many TextBox in my from, so, how can I create a Class for it?
但是,我的 from 中有很多 TextBox,那么,我该如何为它创建一个类呢?
Thanks
谢谢
采纳答案by Derek Tomes
All you need to do is inherit from the TextBox control.
您需要做的就是从 TextBox 控件继承。
Public Class TextBoxEx
Inherits TextBox
Private Sub TextBoxEx_Enter(sender As Object, e As EventArgs) Handles Me.Enter
Me.BackColor = Color.LightCyan
End Sub
Private Sub TextBoxEx_Leave(sender As Object, e As EventArgs) Handles Me.Leave
If Me.Text <> "" Then
Me.BackColor = Color.LightGreen
Else
Me.BackColor = Color.White
End If
End Sub
End Class
Build your project and then replace your TextBox controls with the new TextBoxEx control.
构建您的项目,然后用新的 TextBoxEx 控件替换您的 TextBox 控件。
回答by Okura
You can create a class that has a collection of textbox controls. You can get this collection going through the Controls property of your Form or user control and verifying the type of the control. Internally the class must subscribe to the events you've listed, of the textbox controls collection. Finally, on the methods that handle the events you must write the logic that change the color accordingly. Remember that the handle events methods have the control that triggered the event on the first parameter.
您可以创建一个具有文本框控件集合的类。您可以通过 Form 或用户控件的 Controls 属性获取此集合并验证控件的类型。在内部,该类必须订阅您列出的文本框控件集合的事件。最后,在处理事件的方法上,您必须编写相应地更改颜色的逻辑。请记住,处理事件方法具有在第一个参数上触发事件的控件。
I can go into more detail if you have more doubts.
如果您有更多疑问,我可以更详细地介绍。