Source codeClick here for download
In the design formProgramComplex data is often transferred between mutually called forms, and sometimes the contents of the parent form must be modified by the child form.A while ago, I saw a lot of people discussing this issue in my blog. In my comment on "Inter-form value transfer and inter-form interoperability", I saw several practices: 1) publish a static variable; 2) create a public field in the child form; 3) Use delegation and events in the parent form; 4) use the child form as a member of the parent form.
I don't feel very good about these methods. This will cause the parent form to be too tightly coupled with the child form. to modify any form, re-compile another form. According to the "Dependency inversion" principle, by introducing a result object, we can avoid this tight coupling and transmit any complicated data. If you need to change the status of the parent form in the child form, you can also define the delegate and event in the result object to achieve the goal. Here is my solution.
First, define a result object to store the results returned by the subform. Define some events at the same time, so that the child form can modify the status of the parent form.CodeAs follows:
Using System;
Namespace Winparam
{
Public Delegate Void Textchangedhandler ( String S );
Public Class Cresult
{
Public String Result1 = "" ;
Public String Result2 = "" ;
Public Event Textchangedhandler textchanged;
Public Void Changetext ( String S)
{
If(Textchanged! = Null)
Textchanged (s );
}
}
}
Add a subform constructor to receive a result object:
Private Cresult R;
Public Frmchild (cresult R ): This ()
{
This. R=R;
}
Create a child form in the parent form and subscribe to the cresult event:
Private Void Btncallchild_click ( Object Sender, system. eventargs E)
{
Cresult R = New Cresult ();
R. textchanged + = New Textchangedhandler ( This . Eventresultchanged );
Frmchild FC = New Frmchild (R );
FC. showdialog ();
Txtcallresult. Text = " The result is: " + R. result1 + " " + R. result2;
}
Private Void Eventresultchanged ( String S)
{
Txteventresult. Text=S;
}
This ensures that the parent form knows the child form, while the child form does not know the parent form. After the parent form is changed, you do not need to recompile the child form. Both forms depend on the result object. The stability of the result object also determines the stability of the relationship between the parent form and the child form. The program running result is as follows:
Note: The provided code is only a function demonstration. If you need to add additional auxiliary code (such as releasing objects and canceling event subscriptions ).
Lu Zhenyu
Follow-0
Fans-30 followers
0 0
0
(Please
Article Make comments)