且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从其他表单实例化MDI父级

更新时间:2023-12-06 09:40:28

重新加入的代码:Form2代码

Codes for reattch: Form2 Codes
//Instantiating Form1
Form1 frm1 = new Form1();
this.MdiParent = frm1;



每当我重新连接时,这都是问题孩子没有任何反应。



不,它不会。

因为你正在重新连接Form1的实例不是原始的,甚至不显示 - 这是一个完全不同的实例!关键字 new 在这里应该为您提供一个线索。 :笑:



这就像一辆车:如果你把手机放在汽车的手套箱里,然后把它卖给买一辆新车,你会期待吗?在新车手套箱中找到你的手机?



当你分离form2时,要么保存Parent实例并使用该实例进行重新连接,要么更好在Form2中创建一个事件,要求父母分离并重新附加表单。这样,form2不需要知道它的父级。


this is the problem whenever I reattach the child form nothing happens.

No, it won't.
Because the instance of Form1 that you are "reattaching" to is not the original, and is not even displayed - it is a totally different instance! The keyword new here should give you a clue about this. :laugh:

It's like a car: if you put your mobile phone in the glove box of your car, and sell it to buy a new car, would you expect to find your phone in the new cars glove box?

When you "detach" the form2, either save the Parent instance and use that instance for reattaching, or better still create a events within Form2 which ask the Parent to detach and reattach the form. That way, form2 does not need to know about it's parent.