2017-07-17 96 views
0

我有一个WinForms应用程序,它将不同的窗体作为MDI子窗体处理,并将它们作为标签打开。与打开每个表单的一个实例相关的所有内容实际上都是正确处理的,但是当我抛出“配置文件更改事件”时,我遇到了问题。如何在WinForms中获取MDI Child的原始表单实例?

我想在关闭它之前访问每个子项的实例上的属性,但我只是访问表单,而不是原始对象表单实例本身。

实际代码:

private void ProfileChanged() 
{ 
    foreach (var child in this.MdiChildren) 
    { 
     child.Close(); 
    } 
} 

所需的代码:

private void ProfileChanged() 
{ 
    foreach (var child in this.MdiChildren) 
    { 
     child.Status ... 
     child.Close(); 
    } 
} 

任何想法?非常感谢。

回答

3

您应该将child变量转换为您自定义的Form类型。我想你有一个基本形式,所有的孩子形式继承,对吗?如果不是,你应该有一个基类。

之后,代码应该很简单:

private void ProfileChanged() 
{ 
    //if you want to use Linq 
    foreach (var child in this.MdiChildren.Cast<YourCustomBaseClass>) 
    { 
     child.Status ... 
     child.Close(); 
    } 
    //if you don't want to use Linq 
    foreach (var child in this.MdiChildren) 
    { 
     var myCustomChild = child as YourCustomBaseClass; 
     if (myCustomChild == null) continue; //if there are any casting problems 
     myCustomChild.Status ... 
     myCustomChild.Close(); 
    } 

} 
+0

感谢您的回复。我终于需要做一个this.MdiChildren.Select(frm => frm作为frmBaseEntity)而不是.Cast :) – Gonzo345

0

你可以投你的孩子Formxxx ...其中Formxxx是每个窗体 的类型。例如:

public partial class Form1 : Form 
{ 
    public int Status { get; set; } 
    public Form1() 
    { 
     InitializeComponent(); 

    } 

    private void ProfileChanged() 
    { 
     foreach (var child in this.MdiChildren) 
     { 
      if (child is Form1) 
      { 
      (child as Form1).Status = 1; 
       child.Close(); 
      } 
     } 

    } 
}