Skip to main content
 首页 » 编程设计

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

2024年02月06日13arxive

如何全局设置win窗体所有文本框的背景色? 我们可以将它设置在全局变量中的某个地方并在需要时使用吗? 我需要从全局变量中设置 form_load 中控件的背景颜色,而不是编写

mytextbox1.BackColor = Color.Red; 
mytextbox2.BackColor = Color.Red;  

请您参考如下方法:

 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); 
 } 

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

    private void YourForm_Load(object sender, EventArgs e) 
    { 
        SetRedColorToTextBoxes(); 
    } 

编辑 添加一个 .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); 
    } 
} 

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

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