2

我正在做一个应用程序,用户在文本框中输入一个值,然后他按下一个按钮,两者都在同一个用户控件中。然后文本框的结果将显示在其他用户控件的标签上。两个用户控件都在同一个窗体中。

谢谢!

用户界面图片

在此处输入图像描述

4

2 回答 2

3

最常见的方法是使用事件。我会这样做:

首先定义一个 EventArgs:

public class MyEventArgs : EventArgs
{
    public string Text { get; private set; }

    public MyEventArgs(string Text)
    {
        this.Text = Text;
    }
}

然后在您的 UserControl (带有按钮的那个)中:

public partial class MyUserControl
{
    public event EventHandler<MyEventArgs> ButtonClicked;

    public MyUserControl()
    {
        //...

        button1.Click += (o, e) => OnButtonClicked(new MyEventArgs(textBox1.Text));
    }

    protected virtual void OnButtonClicked(MyEventArgs args)
    {
        var hand = ButtonClicked;
        if(hand != null) ButtonClicked(this, args);
    }
}

然后在表单中订阅您的MyUserControl.ButtonClicked事件并调用第二个控件中的方法。


请注意,如果按钮的行为和文本框中的文本实际上相关,则可以使用属性来获取输入的文本,并将EventArgs事件留空。

PS 名称MyEventArgsMyUserControlButtonClicked仅用于演示目的。我鼓励您在代码中使用更具描述性/相关性的命名。

于 2013-01-27T05:35:39.033 回答
1

试试这个:

public class FirstUserControl:UserControl
{
    Public event EventHandler MyEvent;

    //Public property in your first usercontrol
    public string MyText
    {
        get{return this.textbox1.Text;} //textbox1 is the name of your textbox
    }

    private void MyButton_Clicked(/* args */)
    {
        if (MyEvent!=null)
        {
            MyEvent(null, null);
        }
    }
    //other codes
}


public class SecondUserControl:UserControl
{
    //Public property in your first usercontrol
    public string MyText
    {
        set{this.label1.Text = value;} //label1 is the name of your label
    }

    //other codes
}

然后在您的 MainForm 中:

public class MainForm:Forms
{
    //Add two instance of the UserControls

    public MainForm()
    {
        this.firstUserControl.MyEvent += MainWindow_myevent;
    }

    void MainWindow_myevent(object sender, EventArgs e)
    {
        this.secondUserControl.MyText = this.firstUserControl.MyText;
    }

    //other codes
}
于 2013-01-27T05:45:55.400 回答