[英]How to pass an instance of a form to another form
I have a form called form1
with controls which are created during run-time. 我有一个名为form1
的窗体,其中包含在运行时创建的控件。
When I press a button on the Form another Form loads called combat
and form1
is hidden so that only 1 form ( combat
) is visible. 当我按下“表单”上的按钮时,另一个名为“ combat
表单加载,并且“ form1
被隐藏,因此只有1个表单(“ combat
)可见。
When I press a button on combat
I want my form1
form the be shown. 当我在combat
按下按钮时,我希望显示我的form1
表格。 However I can't access it. 但是我无法访问它。
Here is what I've tried: 这是我尝试过的:
private void combatBtn_Click(object sender, EventArgs e)
{
Form combat = new Combat(this);
this.Hide();
combat.Show();
}
public partial class Combat : Form
{
public Combat(Form form)
{
InitializeComponent();
form.Show();
}
private void button1_Click(object sender, EventArgs e)
{
form.Show();
}
}
您需要将父表单存储在一个字段中,以便可以在构造函数之外访问它。
public partial class Combat : Form
{
private form1 form; // Or whatever class you form1 is supposed to be
public Combat(Form form)
{
InitializeComponent();
this.form = form;
}
private void button1_Click(object sender, EventArgs e)
{
form.Show();
}
}
It's generally not advisable to pass an instance of a parent form to a child. 通常不建议将父窗体的实例传递给孩子。 In this case (as is often true) the code is actually simpler when you don't: 在这种情况下(通常是这样),当您不这样做时,代码实际上会更简单:
private void combatBtn_Click(object sender, EventArgs e)
{
Form combat = new Combat();
this.Hide();
combat.ShowDialog();
this.Show();
}
If you need to show the parent form before the child form is closed then you can do so through events: 如果需要在关闭子窗体之前显示父窗体,则可以通过事件进行显示:
in Combat
add: 在Combat
添加:
public event Action MyEvent; //TODO rename to a meaningful name
Fire the event in the button click handler: 在按钮单击处理程序中触发事件:
private void button1_Click(object sender, EventArgs e)
{
MyEvent();
}
And then have your main form add a handler to the event: 然后让您的主窗体向事件添加处理程序:
private void combatBtn_Click(object sender, EventArgs e)
{
Combat combat = new Combat();
this.Hide();
combat.MyEvent += () => this.Show();
combat.Show();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.