47 .net c# parent-child winforms
如何将孩子的值传递回父表单?我有一个字符串,我想传递给父母.
我使用以下方式启动了孩子
FormOptions formOptions = new FormOptions();
formOptions.ShowDialog();
Mit*_*eat 60
创建一个属性(或方法)FormOptions,比如说GetMyResult:
using (FormOptions formOptions = new FormOptions())
{
    formOptions.ShowDialog();
    string result = formOptions.GetMyResult;
    // do what ever with result...
}
Mus*_*sis 34
如果您只是使用formOptions选择单个值然后关闭,Mitch的建议是一个很好的方法.如果您需要孩子在保持开放的同时与父母沟通,我将使用此示例.
在父表单中,添加子表单将调用的公共方法,例如
public void NotifyMe(string s)
{
    // Do whatever you need to do with the string
}
接下来,当您需要从父级启动子窗口时,请使用以下代码:
using (FormOptions formOptions = new FormOptions())
{
    // passing this in ShowDialog will set the .Owner 
    // property of the child form
    formOptions.ShowDialog(this);
}
在子表单中,使用此代码将值传递回父表:
ParentForm parent = (ParentForm)this.Owner;
parent.NotifyMe("whatever");
此示例中的代码更适用于类似工具箱窗口的内容,该窗口旨在浮动在主窗体上方.在这种情况下,您将使用.Show()而不是.ShowDialog()打开子窗体(使用.TopMost = true).
这样的设计意味着子表单与父表单紧密耦合(因为子表单必须将其所有者强制转换为ParentForm才能调用其NotifyMe方法).但是,这并不是一件坏事.
小智 23
您还可以创建公共属性.
// Using and namespace...
public partial class FormOptions : Form
{
    private string _MyString;    //  Use this
    public string MyString {     //  in 
      get { return _MyString; }  //  .NET
    }                            //  2.0
    public string MyString { get; } // In .NET 3.0 or newer
    // The rest of the form code
}
然后你可以得到它:
FormOptions formOptions = new FormOptions();
formOptions.ShowDialog();
string myString = formOptions.MyString;
您还可以在子类中创建一个ShowDialog重载,它会获取一个返回结果的out参数.
public partial class FormOptions : Form
{
  public DialogResult ShowDialog(out string result)
  {
    DialogResult dialogResult = base.ShowDialog();
    result = m_Result;
    return dialogResult;
  }
}
| 归档时间: | 
 | 
| 查看次数: | 93596 次 | 
| 最近记录: |