如何将字符串或值从用户控件传递到 C# 中的主窗体

how to pass string or value from usercontrol to main form in C#

我创建了一个包含许多按钮的用户控件,并且在主窗体中有一个文本框。 我将 usercontrol 添加到主窗体,我想单击 usercontrol 上的任何按钮,并让主窗体中的文本框显示按钮文本。 问题是如何将用户控件中按钮的字符串传递给主窗体中的文本框? This is what I'm trying to do

public partial class UserControl1 : UserControl
{
    public UserControl1()
    {
        InitializeComponent();

    }
    public string a ;




    private void button1_Click(object sender, EventArgs e)
    {
        a = button1.Text;
    }

    private void button2_Click(object sender, EventArgs e)
    {
        a = button2.Text;
    }

    private void button3_Click(object sender, EventArgs e)
    {
        a = button3.Text;


    }

主窗体代码为:

 private void textBox1_TextChanged(object sender, EventArgs e)
    {
        textBox1.Text = usrCtrl.a;
        // usrCtrl come from : Usercontrol1 usrCtrl = new Usercontrol1();
    }

文本框中什么也没有显示。

您更改 textBox1.Text 值的代码在错误的事件处理程序中。

textBox1_TextChanged 事件处理程序仅在该字段中的文本更改时触发。

您需要做的是输入以下行:

textBox1.Text = a;

在点击事件处理程序中。

参考这个answer,你需要创建一个属性改变的事件。

UserControl.cs class;

public partial class UserControl1 : UserControl
    {
        public event PropertyChangedEventHandler PropertyChanged;
        public UserControl1()
        {
            InitializeComponent();
        }

        private string stringA;

        public string a
        {
            get { return stringA; }
            set
            {
                if (value != stringA)
                {
                    stringA = value;
                    if (PropertyChanged!= null)
                    {
                       PropertyChanged(this, new PropertyChangedEventArgs(a));
                    }
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            a = button1.Text;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            a = button2.Text;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            a = button3.Text;
        }

        private void button4_Click(object sender, EventArgs e)
        {
            a = button4.Text;
        }
    }

在Form的Load我们需要定义事件,

 private void Form1_Load(object sender, EventArgs e)
        {
            cntr.PropertyChanged += Cntr_PropertyChanged; // press tab + tab after += and it will generate the following method automatically.
        }

这是活动;

 private void Cntr_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            textBox1.Text = cntr.a.ToString(); //cntr is the instance of UserControl1

        }

希望有所帮助,