使用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
并创建控件在您的课程中声明并设置其属性。
因此,Constructor
中的代码将无法运行。设计器仅创建表单基类的实例,而不查看表单的构造函数。
设计师如何工作的有趣例子
查看下面的代码,并注意以下问题:
;
在哪里?Form111111
的构造器Form1
?
什么是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
}
}
您将在设计器中看到该表单:
如何在设计时动态添加控件?
如果需要此类功能,则可以在表单的基类的构造函数中创建动态控件,因为当在设计器中打开子窗体时,基类的构造函数将运行,然后在设计时运行。
但是您应该知道这些控件是继承的,并且不能使用子窗体的设计器进行更改。
因此,只需创建一个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 Text Templates。
您可以使用t4模板在设计时生成代码。可能您已经看到了Entity Framework .tt
模板文件。您可以将新的Text Template
项添加到项目中,并将在设计时生成项的逻辑放在t4模板中。
我在remove()方法上遇到问题。我无法删除$(this)对象。我的代码是:$(".submit_add_type").live("click", function() { var parent = $(this).parent(); var type_value = parent.children('.t…
Windows Phone WNS通知导航到特定页面 - c#它是Windows运行时,Windows Phone专用项目。我正在使用Azure和Azure通知中心。所以我的问题是,有谁愿意如何导航到某些特定页面并发送ID等参数。这是我的吐司模板,如字符串中所述: var toast = @"<toast><visual><binding template=""…
当回复有时是一个对象有时是一个数组时,如何在使用改造时解析JSON回复? - java我正在使用Retrofit来获取JSON答复。这是我实施的一部分-@GET("/api/report/list") Observable<Bills> listBill(@Query("employee_id") String employeeID); 而条例草案类是-public static class…
改造正在返回一个空的响应主体 - java我正在尝试使用Retrofit和Gson解析一些JSON。但是,我得到的响应机构是空的。当我尝试从对象中打印信息时,出现NullPointerException。我确保URL正确,并且我也确保POJO也正确。我正在使用jsonschema2pojo来帮助创建POJO类。这是我要解析的JSON{ "?xml": { "@versi…
Windows 8 Metro应用程序的图表 - c#As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely …