在设计视图中以WinForms应用程序以编程方式添加显示控件?
使用Visual Studio(任何版本都可以),是否可以在切换回设计视图时以编程方式(而不是通过“设计”视图)添加控件?
我尝试过一些非常简单的事情:
public Form1() { AddCtrl(); InitializeComponent(); AddCtrl(); } private void AddCtrl() { this.SuspendLayout(); this.Controls.Add(new TextBox()); this.ResumeLayout(false); this.PerformLayout(); }
……但无济于事。
虽然我确信以前曾经问过,因为这似乎是一个常见的问题,但我似乎无法找到答案!
设计师是否运行我的代码?
当表单在设计器中显示时,设计器反序列化表单的代码(Form1.Designer.cs或Form1.cs中的第一个类)并创建表单基类的实例并反序列化InitializeComponent
并创建您声明的控件你的class级并设置他们的属性。
因此, Constructor
的代码将不会运行。 设计者只创建表单基类的实例,而不是查看表单的构造函数。
设计师如何运作的有趣例子
看下面的代码并注意这个问题:
- 在哪里
;
S’ -
Form1
构造函数Form111111
? - 什么是
NotDefinedFunction()
? -
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 } }
你会看到设计师的forms:
如何在设计时动态添加控件?
如果需要这样的function,可以在表单的基类的构造函数中创建动态控件,因为基类的构造函数将在设计器中打开子表单时运行,然后它将在设计时运行。
但是您应该知道这些控件是inheritance的,并且不能使用子窗体的设计器进行更改。
所以只需创建一个Form2:
public Form2() { InitializeComponent(); AddDynamicControls(); } private void AddDynamicControls() { this.Controls.Add( new TextBox() { Name = "TextBox1", Text = "Dynamic", Location = new Point(100, 0) }); }
构建项目,然后将Form1
基类更改为从Form2
inheritance:
public class Form1:Form2
结果将是:
还有其他解决方案吗?
如果你想在设计时真正生成一些控件,我想你应该看看T4文本模板 。
您可以使用t4模板在设计时生成代码。 可能你已经看过Entity Framework .tt
模板文件。 您可以将新的Text Template
项添加到项目中,并在设计时将生成项的逻辑放在t4模板中。