将一个字符串从MDI父级传递给子级的模式对话框

时间:2013-09-16 15:56:55

标签: c# winforms modal-dialog mdichild mdiparent

如何将字符串从MDI父级传递给子级的模式对话框?

打开孩子的MDI父代码:

Form1 f1 = new Form1();
f1.MdiParent = this;
f1.Show();

用于打开模式对话框的Form1代码

Form2 f2= new Form2();
f2.ShowDialog();

2 个答案:

答案 0 :(得分:0)

如果您始终将表单用作模式表单,则可以使用与此类似的模式。

    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

这种模式隔离了你使用" private"的方式。形式的数据,可以很容易 如果您决定添加mors返回值,则会扩展。如果你有更多的输入参数,可以将它们捆绑到一个类中,并将该类的实例传递给Exec方法

答案 1 :(得分:0)

通过使用每个级别的属性来传递它:

//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();

现在,沿途的每个表单都有你传递的字符串的副本。