Windows窗体应用程序中两个用户控件之间的交互

时间:2015-07-20 02:48:37

标签: c# .net winforms user-controls

我创建了两个名为UserControl1UserControl2的用户控件,UserControl1包含TextBox1UserControl2包含Button1。在UserControl2中,我想点击TextBox1.Text时从UserControl1获得Button1

这是令人敬畏的代码: 在UserControl1

 public partial class UserControlA: UserControl
{
    public UserControlA()
    {
        InitializeComponent();
    }

    public string TexBoxText
    {
        get
        {
            return this.textBox1.Text;
        }
    }
}

UserControl2

 public partial class UserControlB: UserControl
{
    public UserControlB()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        //here is to get textbox1.text
    }
}

我该怎么办?

2 个答案:

答案 0 :(得分:0)

一个选项是将UserControlA实例传递给UserControlB的构造函数。

public partial class UserControlB: UserControl
{
    UserControlA userControlA;

    public UserControlB(UserControlA ucA)
    {
        userControlA = ucA;
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        string myString = userControlA.TexBoxText;
    }
}

答案 1 :(得分:0)

UserControl1

public partial class UserControl1 : UserControl
{
    public UserControl1()
    {
        InitializeComponent();
    }
    public TextBox TextBox
    {
        get
        {
            return textBox1;
        }
    }
}

UserControl2

public partial class UserControl2 : UserControl
{
    private TextBox txt = null;
    public UserControl2()
    {
        InitializeComponent();
    }
    public TextBox TextBox
    {
        set
        {
            txt = value;
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (txt != null)
            MessageBox.Show(txt.Text);
    }
}

在上述控制中'容器:

uc2.TextBox = uc1.TextBox;