设计师会运行我的代码吗?
当表单在设计器中显示时,设计器会反序列化表单的代码(Form1.Designer.cs 或 Form1.cs 中的第一类)并创建表单基类的实例并反序列化InitializeComponent
并创建您在类中声明的控件并设置它们的属性。
所以代码中Constructor
不会运行。设计器仅创建表单基类的实例,而不查看表单的构造函数。
设计师如何工作的有趣例子
看下面的代码,注意这个问题:
- 在哪
;
s?
- 构造函数
Form111111
for Form1
?
- What is
NotDefinedFunction()
?
- How can
int i = "xxxxxxxxxx"
?
即使您创建了这样的文件,设计器也会正确显示。
using System
using System.Collections.Generic
using System.Drawing
using System.Windows.Forms
namespace Sample
{
public class Form1:Form
{
public Form111111()
{
NotDefinedFunction()
InitializeComponent()
}
public void InitializeComponent()
{
int i = "xxxxxxxxxx"
this.textBox1 = new System.Windows.Forms.TextBox()
this.SuspendLayout()
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(0, 0)
this.textBox1.Name = "textBox1"
this.textBox1.Text = "text of text box 1";
//
// Form1
//
this.Controls.Add(this.textBox1)
this.Name = "Form1"
this.Text = "Form1"
this.Size= new Size(250,100)
this.ResumeLayout(false)
this.PerformLayout()
}
private TextBox textBox1
}
}
您将在设计器中看到该表单:
如何在设计时动态添加控件?
如果您需要这样的功能,您可以在表单的基类构造函数中创建动态控件,因为当您在设计器中打开子窗体时,基类的构造函数将运行,然后它将在设计时运行。
但您应该知道这些控件是继承的,不能使用子窗体的设计器进行更改。
所以只需创建一个Form2:
public Form2()
{
InitializeComponent();
AddDynamicControls();
}
private void AddDynamicControls()
{
this.Controls.Add(
new TextBox() {
Name = "TextBox1", Text = "Dynamic", Location = new Point(100, 0) });
}
构建项目,然后更改基类Form1
继承自Form2
:
public class Form1:Form2
结果将是:
还有其他解决办法吗?
如果你想在设计时真正生成一些控件,我认为你应该看看.
您可以使用 t4 模板在设计时生成代码。也许你见过实体框架.tt
模板文件。您可以添加新的Text Template
item 到您的项目中,并将设计时生成项目的逻辑放入您的 t4 模板中。