【问题标题】:Change properties of any control within a parent form更改父窗体中任何控件的属性
【发布时间】:2012-05-04 19:41:44
【问题描述】:

有谁知道如何从父表单调用任何对象(标签、文本框、面板)。例如,我有一个表单 A,这个表单有一个标签 L、文本框 T 和按钮 B。我是否可以通过函数(public DoSomething(Form f))传递整个表单,然后更改标签 L 的属性,函数 DoSomething 中的文本框 T 和按钮 B?

class DoSomething{
 private Form parentForm;
 public DoSomething(Form f) {
   parentForm = f;
   // HERE I WOULD LIKE TO CHANGE PROPERTIES OF LABEL L, BUTTON B
 }
}

【问题讨论】:

  • 请不要在您的标题前加上“C#”之类的前缀。这就是标签的用途。

标签: c# winforms controls


【解决方案1】:

您可以遍历所有表单控件并更改每个控件的属性:

foreach (Control c in parentForm.Controls)
{
   if (c is Label && c.Name == "L")
   {
       // Do label stuff here
   }
   else if (c is TextBox && c.Name == "T")
   {
       // Do text box stuff here
   }
   if (c is Button && c.Name == "B")
   {
       // Do button stuff here
   }
}

如果你想通过名字找到控件,你可以试试这个:

Label L = (Label)parentForm.Controls.Find("L");
TextBox T = (TextBox)parentForm.Controls.Find("T");
Button B = (Button)parentForm.Controls.Find("B");

// Do stuff with L, T and B here...

【讨论】:

    【解决方案2】:

    您面临的问题是 Form 类没有包含您感兴趣的属性。

    Indise DoSomething 您必须将表单转换为原始类型才能访问其控件:

     if (f is Form1)
     {
        Form1 f1 = f as Form1;
        f1.C... // here all the properties of the class form1 Are available.
     }
    

    如果所有表单都有共同的属性,您可以创建一个接口,并在所有表单中实现它。并将你的DoSomething的参数类型设置为接口的类型:

    void DoSomething(IFomrInterface fi)
    {
      fi.C... // this will have all the propertie savailabel in the interface
    }
    

    第二种解决方案更通用。所有的表单都应该实现接口:

    class Form1: Form, IFormInterface
    

    【讨论】:

      【解决方案3】:

      尝试将父表单属性的控件设置为Modifier to Public

      在子窗体中,用作

      parentForm.btnA.Name="ButtonB";
      

      希望它有效!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-02-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-15
        • 1970-01-01
        • 2020-01-26
        相关资源
        最近更新 更多