-
06-09-2019 - |
题
我有一个用 C# 创建的组件,该组件以前使用默认构造函数,但现在我希望它的父窗体通过传递对其自身的引用来创建对象(在设计器中)。
换句话说,而不是在 Designer.cs 中使用以下内容:
this.componentInstance = new MyControls.MyComponent();
我想指示表单设计者创建以下内容:
this.componentInstance = new MyControls.MyComponent(this);
是否可以实现这一点(最好通过某些属性/注释或其他东西)?
解决方案
你不能简单地使用 控制.父级 财产?当然,它不会在控件的构造函数中设置,但克服这个问题的典型方法是实现 ISupport初始化 并在做工作 结束初始化 方法。
为什么需要返回欠款控制的参考?
在这里,如果您创建一个新的控制台应用程序,并粘贴此内容以替换 Program.cs 的内容,然后运行它,您会注意到 .EndInit, , 这 家长 属性设置正确。
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());
}
}
}
其他提示
我不知道实际上有设计师以任何方式发出代码中调用非默认的构造函数,但这里的一个想法绕过它。把你的初始化代码父窗体的默认构造函数内部,使用Form.DesignMode来看看你是否需要执行它。
public class MyParent : Form
{
object component;
MyParent()
{
if (this.DesignMode)
{
this.component = new MyComponent(this);
}
}
}
不隶属于 StackOverflow