从子表单更改父表单的标签文本

Mil*_*ind 2 .net c#

可能重复:
从子窗体访问父窗体上的控件

我有父表单form1和子表单test1我想从父表单中的子表单更改父表单的标签文本我有showresult()的方法

public void ShowResult() { label1.Text="hello"; }

我想label.Text="Bye";在按钮点击事件上更改我的子表单test1.请提出任何建议.

Tal*_*lha 8

在调用子表单时,Parent像这样设置子表单对象的属性.

Test1Form test1 = new Test1Form();
test1.Show(this);
Run Code Online (Sandbox Code Playgroud)

在您的父表单上,将标签文本的属性设置为..

public string LabelText
{
  get
  {
    return  Label1.Text;
  }
  set
  {
    Label1.Text = value;
  }
}
Run Code Online (Sandbox Code Playgroud)

从您的子表单中,您可以获得类似的标签文本.

((Form1)this.Owner).LabelText = "Your Text";
Run Code Online (Sandbox Code Playgroud)


Jus*_*vey 5

毫无疑问,有很多捷径可以做到这一点,但在我看来,一个好的方法是从子表单引发一个请求父表单更改显示文本的事件。父表单应该在创建子表单时注册此事件,然后可以通过实际设置文本来响应它。

所以在代码中这看起来像这样:

public delegate void RequestLabelTextChangeDelegate(string newText);

public partial class Form2 : Form
{
    public event RequestLabelTextChangeDelegate RequestLabelTextChange;

    private void button1_Click(object sender, EventArgs e)
    {
        if (RequestLabelTextChange != null)
        {
            RequestLabelTextChange("Bye");
        }
    }        

    public Form2()
    {
        InitializeComponent();
    }
}


public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        Form2 f2 = new Form2();
        f2.RequestLabelTextChange += f2_RequestLabelTextChange;
    }

    void f2_RequestLabelTextChange(string newText)
    {
        label1.Text = newText;
    }
}  
Run Code Online (Sandbox Code Playgroud)

它有点冗长,但它使您的孩子形式与其父母的任何知识脱钩。这是一个很好的可重用模式,因为这意味着子表单可以在另一个主机(没有标签)中再次使用而不会中断。