在控件中定义标签.加入c#

本文关键字:加入 标签 定义 控件 | 更新日期: 2023-09-27 18:06:15

我希望定义一个一次性标签,同时将其添加到控件,这样做的正确语法是什么?

例如像这样:

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

在控件中定义标签.加入c#

删除属性前的.

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

msdn中的对象初始化项

对象和集合初始化项

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

确保label1存在,所以,不要在InitializeComponent()之前调用它

当你使用对象初始化器标签控件时,你不需要"。设置属性的值。

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