如何在全局 C# 中为 winform 中的所有文本框设置背景色?

Pra*_*hap 1 c# winforms

如何在全局范围内为win形式的所有文本框设置背景颜色?我们可以将它设置在全局变量中并在需要时使用吗?我需要从全局变量而不是编写 form_load 中设置控件的背景颜色

mytextbox1.BackColor = Color.Red;
mytextbox2.BackColor = Color.Red; 
Run Code Online (Sandbox Code Playgroud)

Ars*_*had 5

 private void SetRedColorToTextBoxes()
 {
     Action<Control.ControlCollection> func = null;

     func = (controls) =>
         {
             foreach (Control control in controls)
                 if (control is TextBox)
                     (control as TextBox).BackColor = Color.Red;
                 else
                     func(control.Controls);
         };

     func(Controls);
 }
Run Code Online (Sandbox Code Playgroud)

SetRedColorToTextBoxes()在表单加载中调用函数。

    private void YourForm_Load(object sender, EventArgs e)
    {
        SetRedColorToTextBoxes();
    }
Run Code Online (Sandbox Code Playgroud)

编辑 添加一个 .cs 文件并将代码放在那里。

  class Helper
   {
    public void SetRedColorToTextBoxes(Form frm)
    {
        Action<Control.ControlCollection> func = null;

        func = (controls) =>
        {
            foreach (Control control in controls)
                if (control is TextBox)
                    (control as TextBox).BackColor = Color.Red;
                else
                    func(control.Controls);
        };

        func(frm.Controls);
    }
}
Run Code Online (Sandbox Code Playgroud)

并将其称为您的表单加载:

 private void YourForm_Load(object sender, EventArgs e)
    {
        // this means instance of  currentform.
       (new Helper()).SetRedColorToTextBoxes(this);
    }
Run Code Online (Sandbox Code Playgroud)