2009-06-01 199 views
1

我有一个我在C#中创建的组件,它以前一直使用默认的构造函数,但现在我希望它的父窗体通过传递自身的引用来创建对象(在设计器中) 。非默认构造函数

换句话说,而不是在designer.cs如下:

 this.componentInstance = new MyControls.MyComponent(); 

我想指示表单设计器创建以下文件:

 this.componentInstance = new MyControls.MyComponent(this); 

是否有可能实现这(最好通过一些属性/注释或东西)?

回答

2

难道你不能简单地使用Control.Parent属性?当然,它不会在您的控件的构造函数中设置,但解决该问题的典型方法是通过执行ISupportInitialize并执行EndInit方法中的工作。

为什么你需要参考回到欠款控制?

在这里,如果您创建一个新的控制台应用程序并粘贴此内容以替换Program.cs的内容并运行它,您会注意到在.EndInit中,Parent属性已正确设置。

using System; 
using System.Windows.Forms; 
using System.ComponentModel; 
using System.Drawing; 

namespace ConsoleApplication9 
{ 
    public class Form1 : Form 
    { 
     private UserControl1 uc1; 

     public Form1() 
     { 
      uc1 = new UserControl1(); 
      uc1.BeginInit(); 
      uc1.Location = new Point(8, 8); 

      Controls.Add(uc1); 

      uc1.EndInit(); 
     } 
    } 

    public class UserControl1 : UserControl, ISupportInitialize 
    { 
     public UserControl1() 
     { 
      Console.Out.WriteLine("Parent in constructor: " + Parent); 
     } 

     public void BeginInit() 
     { 
      Console.Out.WriteLine("Parent in BeginInit: " + Parent); 
     } 

     public void EndInit() 
     { 
      Console.Out.WriteLine("Parent in EndInit: " + Parent); 
     } 
    } 

    class Program 
    { 
     [STAThread] 
     static void Main() 
     { 
      Application.Run(new Form1()); 
     } 
    } 
} 
+0

谢谢,我不认为要重写EndInit()(我还没有用我自己的组件做很多)。这是我正在寻找的答案。 – Dov 2009-06-02 13:46:27

0

我不知道有什么方法可以让设计者发出调用非默认构造函数的代码,但这里有个想法来解决它。将初始化代码放入父窗体的默认构造函数内,并使用Form.DesignMode查看是否需要执行它。

public class MyParent : Form 
{ 
    object component; 

    MyParent() 
    { 
     if (this.DesignMode) 
     { 
      this.component = new MyComponent(this); 
     } 
    } 
}