如何在不创建新对象的情况下获取表单控件 [英] How Can Get A Form Controls Without Making new Object Of It

查看:87
本文介绍了如何在不创建新对象的情况下获取表单控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我面临的问题

What problem i am facing

public class MyController
      {
          public void Thread_ContinuousChecker()
          {
              Form1 f = new Form1();
//here i want to access the form controls without using new ,
//any suggestion?
//bcz when i use it goes to his original position(at start time position)
//but i want to store the control setting here.

              f.Hide();
              if (f.checkBox3.Checked)
              {
                  Thread th = new Thread(f.files);
                  th.Start();
              }

}
}
}

推荐答案

Windows窗体中的窗体被实例化为窗体的私有成员;这是你不应该忽略的事情,例如,将Designer.cs类中Control的定义设置为'Public。



所以,你可以只能通过以下方式获取表单实例中的控件实例:



1.您创建的公共属性在其托管表单中公开它们:
Controls on a Form, in Windows Forms, are instantiated as private members of the Form; that is something you should not over-ride by, for example, setting the definition of a Control in the Designer.cs Class to 'Public.

So, you can only "get at" the instances of Controls in the instance of a Form by:

1. Your creating public properties that expose them in their hosting Form:
public Form1()
{
    InitializeComponent();
    TheCheckBox = this.checkBox3;
}

// use this to access 'checkBox3 from "outside" the Form
public TheCheckBox { private set; get; }

2。深入到Form实例的Controls Collection并获取对它们的引用。

2. Your drilling-down into the Controls Collection of the Form instance and getting a reference to them.

CheckBox TheCheckBox = null;

var result = f.Controls.Find("checkBox3", searchAllChildren: true);

// note required cast here if search is successful ...
if (result.Length > 0) TheCheckBox = result[0] as CheckBox;


使用static成员。

MSDN [ ^ ]

static Form1 f;
Use "static" member.
MSDN[^]
static Form1 f;


这篇关于如何在不创建新对象的情况下获取表单控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆