如何公开控件的 属性?

How do I expose a control's property publicly?

我想将 Form1 上文本框的文本 属性 公开给 Form2,以便 Form2 可以在 Form1 上的文本框中设置文本。我已经阅读了操作方法,但它不起作用,所以我一定是做错了什么。

这是 Form1 的代码,包括 public 属性 的声明(TextInputText 是 属性,txtInput 是文本框):

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public string TextInputText
        {
            get => txtInput.Text;
            set => txtInput.Text = value;
        }

        public Form1()
        {
            InitializeComponent();                       
        }

        private void txtInput_KeyDown(object sender, KeyEventArgs e)
        {
            // If enter is pressed clear the textbox, but update() the history first

            if (e.KeyCode == Keys.Enter)
            {
                TextHistory.Update(txtInput.Text);
                txtInput.Text = "";
            }
        }

        private void HistoryButton_Click(object sender, EventArgs e)
        {
            Form2 HistoryForm = new Form2();
            HistoryForm.Show();
        }
    }
}

问题是 Form2 仍然看不到 属性,或者我不知道如何访问它,我做错了什么?

您没有为 Form2 提供对 Form1 实例的引用:

Form2 HistoryForm = new Form2();

如何在没有实例的情况下访问 实例 函数、属性 或值?静态 属性 没有意义。因此,最可能的选择是为 Form2 提供一个构造函数,该构造函数将 Form1 引用作为参数。将该引用存储在 Form2 中的某处。然后像这样调用构造函数:

Form2 HistoryForm = new Form2(this);

要么在创建 Form2 时注入对 Form1 的引用:

private void HistoryButton_Click(object sender, EventArgs e)
{
    Form2 HistoryForm = new Form2(this);
    HistoryForm.Show();
}

这需要您在 Form2 中定义接受 Form1 引用的自定义构造函数。然后您可以使用此引用访问 属性:

private readonly Form1 _form1;
public Form2(Form1 form1)
{
    InitializeComponent();
    _form1 = form1;

    string text = _form1.TextInputText;
}

另一种方法是使用 Application.OpenForms 属性 在 Form2:

中获取对 Form1 的引用
var form1 = Application.OpenForms.OfType<Form1>().FirstOrDefault();
string text = form1.TextInputText;