简体   繁体   English

在Controls.Add中定义标签

[英]Defining a label inside Controls.Add in C#

I wish to define a one time label while adding it to controls, whats the correct syntax of doing so? 我希望在将其添加到控件时定义一个一次性标签,这样做的正确语法是什么?

for example something like this: 例如这样的事情:

this.Controls.Add(new Label
{ 
    .BorderStyle = label1.BorderStyle,
    .BackColor = label1.BackColor,
    .Text = "Breaks",
    .Font = label1.Font,
});

Just remove the . 只需删除. before the properties 在属性之前

this.Controls.Add(new Label
{ 
    BorderStyle = label1.BorderStyle,
    BackColor = label1.BackColor,
    Text = "Breaks",
    Font = label1.Font,
});

Object initializer in msdn. msdn中的对象初始化程序

Object and Collection Initializers 对象和集合初始化器

this.Controls.Add(new Label
{ 
    BorderStyle = label1.BorderStyle,
    BackColor = label1.BackColor,
    Text = "Breaks",
    Font = label1.Font,
});

Make sure label1 is exists, so, don't call it before InitializeComponent() 确保label1存在,所以不要在InitializeComponent()之前调用它

As you are using Object Initializer for the label control, you don't require the "." 当您将对象初始化器用于标签控件时,不需要“。”。 to set the values of the properties. 设置属性的值。

Example : Cat cat = new Cat { Age = 10, Name = "Fluffy" }; 范例: Cat cat = new Cat { Age = 10, Name = "Fluffy" }; from MSDN MSDN

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM