【问题标题】:Non-Default Constructor非默认构造函数
【发布时间】:2010-10-30 12:38:17
【问题描述】:

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

换句话说,而不是designer.cs中的以下内容:

        this.componentInstance = new MyControls.MyComponent();

我想指示表单设计者创建以下内容:

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

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

【问题讨论】:

    标签: c# .net visual-studio attributes form-designer


    【解决方案1】:

    您不能简单地使用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());
            }
        }
    }
    

    【讨论】:

    • 谢谢,我没想过要重写 EndInit()(我自己的组件还没有做很多事情)。这就是我一直在寻找的答案。
    【解决方案2】:

    我不知道实际让设计器发出调用非默认构造函数的代码的任何方法,但这里有一个绕过它的想法。把你的初始化代码放在父窗体的默认构造函数里面,用Form.DesignMode看看是否需要执行。

    public class MyParent : Form
    {
        object component;
    
        MyParent()
        {
            if (this.DesignMode)
            {
                this.component = new MyComponent(this);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-23
      • 1970-01-01
      • 2023-03-20
      • 2012-07-26
      • 2015-10-20
      相关资源
      最近更新 更多