通过 Form1 上的按钮更改 UserControl 文本框

Change UserControl textbox through Button on Form1

我有一个名为 Form1 的表单,其中包含一个按钮控件 (bunifuImageButton9) 和一个用户控件 (UserControl1)。用户控件有一个文本框 (textBox2)。我需要按钮来更改用户控件中文本框中的文本。

我知道如何更改普通文本框中的内容,但我不知道如何访问用户控件中的文本框。

我该怎么做?

快速而肮脏且可能是错误的方法是在 textBox2 public 上创建 public 而不是私有 UserControl1,然后从表单中调用

userControl1.textBox2.Text = "some new value";

更正确的做法是在 UserControl1 中添加一个 public 属性 以有意义的方式显示文本框:

class UserControl1 {
    public string SomeCoolTextValue {
        get {
            return textBox2.Text;
        }
        set {
            textBox2.Text = value;
        }
    }
}

class Form1 {
    private void bunifuImageButton9_Click(object sender, EventArgs e) {
        userControl1.SomeCoolTextValue = "some new value";
    }
}