且构网

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

如何将值从子窗体传递到父窗体

更新时间:2023-12-06 09:00:34

这是关于表单协作的常见问题.最健壮的解决方案是在Form类中实现适当的接口,并传递接口引用而不是对Form的整个实例"的引用.请查看我过去的解决方案以获取更多详细信息:如何以两种形式在列表框之间复制所有项目 [ http://en.wikipedia.org/wiki/Accidental_complexity [ http://en.wikipedia.org/wiki/Loose_coupling [
This is the popular question about form collaboration. The most robust solution is implementation of an appropriate interface in form class and passing the interface reference instead of reference to a "whole instance" of a Form. Please see my past solution for more detail: How to copy all the items between listboxes in two forms[^].

Please also see other solutions in this discussion. If the application is simple enough, the solution could be as simple as declaring of some internal property in one form and passing a reference to the instance of one form to the instance of another form. For more complex projects, such violation of strictly encapsulated style and loose coupling could add up the the accidental complexity of the code and invite mistakes, so the well-encapsulated solution would be preferable.

Please see also:
http://en.wikipedia.org/wiki/Accidental_complexity[^],
http://en.wikipedia.org/wiki/Loose_coupling[^].

—SA


取决于显示表单的方式.
如果使用ShowDialog,则很简单:只需在子窗体中创建一个公共属性,然后直接在父窗体中访问它即可:
Depends on how you show your forms.
If you use ShowDialog then it is easy: just create a public property in the child form, and access it directly in the parent:
ChildForm child = new ChildForm();
child.MyProperty = "Hello";
child.ShowDialog();
Console.WriteLine(child.MyProperty);


如果使用Show代替,则难度会稍大一些-您必须创建属性和事件,或者事件和自定义EventArgs

在子窗体中:


If you use Show instead then it is slightly harder - you have to create property and an event, or an event and a custom EventArgs

In the child form:

public partial class frmChild : Form
   {
   public event EventHandler Changed;

   protected virtual void OnChanged(EventArgs e)
      {
      EventHandler eh = Changed;
      if (eh != null)
         {
         eh(this, e);
         }
      }

   private void DoSomethingToChangeData()
      {
      OnChanged(null);
      }
   }

如果处理程序在null检查和exec之间切换(不太可能,但可能),则向eh赋值
空检查是为了确保有一个处理程序.如果不是,***是依赖于抛出的异常(NullReferenceException)优雅地忽略它.

在家长表格中:

The asign to eh is in case the handler changes between null check and exec (unlikely, but possible)
The null check is to ensure there is a handler. If not, better to ignore it gracefully, than to rely on the thrown exception (NullReferenceException)

In the Parent form:

private void ShowChildForm()
    {
    frmChild fd = new frmChild();
    fd.Changed += new EventHandler(Changed);
    fd.Show();
    }
private void Changed(object sender, EventArgs e)
    {
    frmChild fc = sender as frmChild;
    if (fc != null)
       {
       Console.WriteLine(fc.MyProperty);
       }
    }


这可能会有所帮助,
在Windows窗体之间共享数据 [
It might be helpful,
Sharing data among Windows Forms[^]

:)