如何将字符串从 MDI 父级传递给子级的模态对话框?
MDI父代码打开子:
Form1 f1 = new Form1();
f1.MdiParent = this;
f1.Show();
Form1 代码打开模态对话框
Form2 f2= new Form2();
f2.ShowDialog();
如何将字符串从 MDI 父级传递给子级的模态对话框?
MDI父代码打开子:
Form1 f1 = new Form1();
f1.MdiParent = this;
f1.Show();
Form1 代码打开模态对话框
Form2 f2= new Form2();
f2.ShowDialog();
只需通过使用每个级别的属性来传递它:
//Form1 needs a property you can access
public class Form1
{
private String _myString = null;
public String MyString { get { return _myString; } }
//change the constructor to take a String input
public Form1(String InputString)
{
_myString = InputString;
}
//...and the rest of the class as you have it now
}
public class Form2
{
private String _myString = null;
public String MyString { get { return _myString; } }
//same constructor needs...
public Form2(String InputString)
{
_myString = InputString;
}
}
最终,您的电话变成:
String strToPassAlong = "This is the string";
Form1 f1 = new Form1(strToPassAlong);
f1.MdiParent = this;
f1.Show();
Form2 f2= new Form2(f1.MyString); //or this.MyString, if Form2 is constructed by Form1's code
f2.ShowDialog();
现在,沿途的每个表单都有一个您传递的字符串的副本。
如果您总是将表单用作模态表单,则可以使用与此类似的模式。
class FormResult
{
public DialogResult dr {get; private set;}
public string LastName {get; private set;}
public string FirstName {get; private set;}
}
class MyForm : whatever
{
static public FormResult Exec(string parm1, string parm2)
{
var result = new FormResult();
var me = new MyForm();
me.parm1 = parm1;
me.parm2 = parm2;
result.dr = me.ShowDialog();
if (result.dr == DialogResult.OK)
{
result.LastName = me.LastName;
result.FirstName = me.FirstName;
}
me.Close(); // should use try/finally or using clause
return result;
}
}
... rest of MyForm
此模式隔离了您使用表单的“私有”数据的方式,并且如果您决定添加 mors 返回值,则可以轻松扩展。如果您有更多的输入参数,您可以将它们捆绑到一个类中并将该类的实例传递给 Exec 方法