如何引用Designer创建的对象

时间:2013-03-15 00:33:28

标签: c# oop designer

(我正在使用默认的Visual Studio名称)如何在form1.cs文件中的另一个自定义类(“公共部分类Form1:Form”中的类)中引用texbox对象(texbox1)

这是我的代码。在myclass中我写了textBox1,但是intelisense没有向我提出建议。我的意思是。在这种情况下,我该怎么做才能让texbox1在智能上出现?在form1.Desginer.cs中将private更改为public并不解决它。 plaease回答。

namespace Calculator
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent(); 
        }


        class myclass 
        {

           textBox1

        }
}

3 个答案:

答案 0 :(得分:0)

WinForms设计器默认情况下将组件设为私有,理想情况下,您不应直接公开组件(如控件),因为它会破坏封装。您应该代理要共享的字段,如下所示:

public partial class MyForm : Form {

    private TextBox _textbox1; // this field exists in the MyForm.designer.cs file

    // this property should be in your MyForm.cs file
    public String TextBox1Value {
        get { return _textbox1.Text; }
        set { _textbox1.Text = value; }
    }
}

通过这种方式,您可以在表单之间共享数据,但也可以保持封装(尽管您应该选择比我选择的TextBox1Value更具说明性的名称。

答案 1 :(得分:0)

在嵌套类myclass中,您没有指定要引用的Form1类的实例。添加对Form1的特定实例的引用,然后您就可以访问其textBox1成员。

通常,这可以这样做:

class myclass
{
    public myclass(Form1 owner)
    {
        if (owner == null) {
            throw new ArgumentNullException("owner");
        }

        this.owner = owner;
    }

    private readonly Form1 owner;

    public void DoSomething()
    {
        owner.textBox1.Text = "Hello, world!";
    }
}

此代码使用在这种情况下使用的各种模式:

  • owner在构造函数中设置,从而确保从不 null
  • 添加到此,null被构造函数
  • 拒绝
  • owner成员是readonly,因此可以肯定地说,它在给定的myclass实例的生命周期内不会发生变化

Form1的方法中,您可以通过调用myclass创建链接到当前Form1实例的new myclass(this)实例。

答案 2 :(得分:0)

你不能在嵌套类中引用它作为Form1类的一部分,你必须传入一个引用

示例:

class myclass 
{
    public TextBox MyTextBox { get; set; }

    public MyClass(TextBox textbox)
    {
        MyTextBox = textbox;
    }
}

然后,在您创建Form1个实例的MyClass课程中,您可以传入TextBox

MyClass myClass = new MyClass(this.textBox1);