How to refrence an object created by Desginer [dup

2020-01-20 03:10发布

问题:

(I'm using default Visual Studio names) How can I reference a texbox object(texbox1) in another custom class in form1.cs file(a class within "public partial class Form1 : Form")

here is my code. In myclass I've written textBox1, but intelisense didn't suggest it to me. I mean. what can I do to make texbox1 show up in intelisence in this situation? changing private to public in form1.Desginer.cs does'nt solve it. plaease answer.

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


        class myclass 
        {

           textBox1

        }
}

回答1:

The WinForms designer makes components private by default, and ideally you should not expose components (such as controls) directly because it breaks encapsulation. You should proxy fields that you want to share, like so:

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

That way you can share data between forms but also maintain encapsulation (though you should choose a more descrptive name than the TextBox1Value I chose.



回答2:

In your nested class myclass, you do not specify which instance of the Form1 class you are referring to. Add a reference to a particular instance of Form1, then you will be able to access its textBox1 member.

Customarily, this can be done like so:

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!";
    }
}

This code uses various patterns that are used in such situations:

  • owner is set in the constructor, thereby ensuring that it is never null
  • adding to this, null is rejected by the constructor
  • the owner member is readonly, so it is safe to say that it will not change during the lifetime of a given myclass instance

Within a method of Form1, you can then create a myclass instance linked to the current Form1 instance by invoking new myclass(this).



回答3:

You cant just reference it in your nested class as its part of the Form1 class, you will have to pass in a reference

Example:

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

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

Then in your Form1 class where you created the MyClass instance you can pass in your TextBox

MyClass myClass = new MyClass(this.textBox1);