c# - 如何让 Visual Studio 中的设计器使用参数化构造函数生成组件

标签 c# winforms visual-studio-2012

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

例如:

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

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

使用 dotPeek 来反射(reflect) ContextMenuStrip 并没有给我任何有用的方法。

我想制作一个自定义控件,当将其拖放到任何 System.Windows.Forms.Control 时,设计器将调用参数构造函数而不是无参数构造函数。

最佳答案

来自the MSDN page about the design-time features of Windows Forms ,看来具有以 IContainer 作为参数的构造函数的组件是一种特殊情况:

A component can let the designer know that it would like to be notified when its container goes away by implementing a public constructor that takes a single argument of type IContainer, as shown in this snippet:

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); 
    } 
    // ...
}

Notice that the constructor uses the container to add itself as a container component. In the presence of this constructor, the designer will generate code that uses this constructor, passing it a container for the component to add itself to.

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

关于c# - 如何让 Visual Studio 中的设计器使用参数化构造函数生成组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21027443/

相关文章:

c# - NHibernate 上的 CurrentSessionContext

c# - 下载和安装 msi\exe 的最佳最佳方式是什么

c# - C# winforms 中的属性指定资源选择器?

c# - 并排显示数据表列 C# 控制台应用程序

c# - c#的免费报告

c# - 极其简单的 SQLite 查询不返回预期

.net - WinForms - 事件指示器

c++ - Visual Studio 2012 : Syntax Highlighting is turning off and on

vb.net - .exe 不是 Windows XP 上有效的 Win32 应用程序

visual-studio - 使用Visual Studio 2012构建部署包