简体   繁体   中英

How do I expose a control's property publicly?

I want to expose the Text property of a textbox on Form1 to Form2 so Form2 can set the text in the textbox on Form1. I've read how to do it but it doesn't work so I must be doing something wrong.

Here's the code for Form1 including the declaration of the public property (TextInputText is the property, txtInput is the textbox):

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

The problem is Form2 still can't see the property, or I don't know how to access it, what am I doing wrong?

Either inject Form2 with a reference to Form1 when you create it:

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

This requires you to define a custom constructor in Form2 that accepts a Form1 reference. You can then use this reference to access the property:

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

    string text = _form1.TextInputText;
}

Another approach is to use the Application.OpenForms property to get a reference to Form1 in Form2 :

var form1 = Application.OpenForms.OfType<Form1>().FirstOrDefault();
string text = form1.TextInputText;

You do not give Form2 a reference to the Form1 instance:

Form2 HistoryForm = new Form2();

How could you access a Instance Function, Property or Value, without a Instance? A static property would not make sense. So the most likely option is to give Form2 a constructor that takes a Form1 reference as Argument. Store that reference somewhere in Form2. Then call the constructor like this:

Form2 HistoryForm = new Form2(this);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM