C#父母与子女中的MDI表单 [英] MDI form in C# Parent And Child
问题描述
我的项目中有3个表单。
I have 3 forms on my project.
-
form1
是MDI控制器 -
form2
和form3
是MDI儿童
form1
is MDI controllerform2
andform3
are MDI children
如何创建 form1
作为父级和 form2
和 form3
还是孩子?
How do I create form1
as the parent and form2
and form3
as children?
类似于旧MFC的MDI接口:
Something like old MFC's MDI interface:
想象 form2
是父母,并有一个按钮。如果单击,它必须在父窗体( form1
)中打开 form3
。我该如何设置?
Imagine form2
is the parent and has a button. If clicked, it must open form3
in the parent form (form1
). How do I set this up?
推荐答案
首先,确保Form1的 IsMdiContainer
设置为 true
。
Firstly, make sure Form1's IsMdiContainer
is set to true
.
然后实例化Form1和Form2,将Form1设置为Form2的MdiParent:
Then instantiate Form1 and Form2, setting Form1 to be Form2's MdiParent:
// Form1.IsMdiContainer should be true
Form1 form1 = new Form1();
// This automatically adds form2 into form1's MdiChildren collection
Form2 form2 = new Form2();
form2.MdiParent = form1;
在Form2的代码中,具有如下所示的内容来处理按钮的click事件以实例化Form3。
In Form2's code, have something like the following to handle the button's click event to instantiate Form3.
public class Form2 : Form {
// Include as data member so we only instantiate one Form3
Form3 _form3;
public Form2() {
InitializeComponent();
Button1.Click += new EventHandler(Button1_Click);
}
private void Button1_Click(object sender, EventArgs e) {
if(_form3 == null) {
_form3 = new Form3();
// Set Form3's parent to be Form1
_form3.MdiParent = this.MdiParent;
}
}
}
请注意,代码真的很快又很脏。关于它,有一些不良的事情,例如Form2和Form3的耦合(以及无用的类名Form1,Form2和Form3)。理想情况下,您可以通过引发Form2可以挂接到并实例化Form3的事件来使Form2和Form3脱钩。该示例代码旨在为您提供指导。
As a couple notes, this code is really quick and dirty. There are several undesirable things about it like the coupling of Form2 and Form3 (as well as unhelpful class names Form1, Form2, and Form3). Ideally, you'd decouple Form2 and Form3 by raising an event from Form2 that your forms container can hook onto and instantiate Form3. This sample code is meant to give you a direction.
这篇关于C#父母与子女中的MDI表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!