如何在Visual Studio中使用参数化构造函数生成组件

时间:2014-01-09 17:45:59

标签: c# winforms visual-studio-2012

如何使用带参数的构造函数使Visual Studio生成代码?

例如:

添加ContextMenuStrip时,这行代码在MyForm.designer.cs中生成InitializeComponent()

this.MyMenuStrip= new System.Windows.Forms.ContextMenuStrip(this.components);

使用dotPeek反映ContextMenuStrip并没有给我任何有用的方法。

我想创建一个自定义控件,当它被删除到任何System.Windows.Forms.Control时,设计器将调用参数构造函数而不是无参数构造函数。

1 个答案:

答案 0 :(得分:2)

the MSDN page about the design-time features of Windows Forms开始,带有构造函数的组件似乎是一个特殊情况:

  

一个组件可以让设计师知道它想要的   通过实施公众通知其集装箱何时消失   采用IContainer类型的单个参数的构造函数,如图所示   在这个片段中:

class ClockComponent : Component {
    public ClockComponent(IContainer container) { 
        // Add object to container's list so that 
        // we get notified when the container goes away container.Add(this); 
    } 
    // ...
}
  

请注意,构造函数使用容器将其自身添加为   容器组件。在这个构造函数的存在下,设计师   将生成使用此构造函数的代码,并将其传递给容器   为组件添加自己。

另请参阅MSDN上的Customizing Code Generation in the .NET Framework Visual Designers