2013-08-06 79 views
14

我正在使用Visual Studio 2010构建一个非常简单的表单。这一切都工作正常,除了我需要动态绘制标签到窗体上。我可以得出的标签,但是当我尝试和改变newlabel.Font.Size属性,我得到这个错误:无法更改C#中标签的字体大小

Property or indexer 'System.Drawing.Font.Size' cannot be assigned to -- it is read only 

这是什么意思?如何解决呢?这是我第一次使用C#程序,如果我正在做一些非常愚蠢的事情,请尽量减少一些。

这里是我画的标签代码:

Label newlabel = new Label(); 
newlabel.Text = "BOOM"; 
newlabel.Font.Size = 72;//This causes the error 
newlabel.ForeColor = Color.White; 
newlabel.Location = new Point(250,250); 
newlabel.AutoSize = false; 
this.Controls.Add(newlabel); 
+1

你可能需要创建一个新的'Font'大小为'72'和一切从'newlabel.Font'复制(即当前字体)。 –

回答

24

你必须创建一个使用新字体:newlabel.Font = new Font(fontFamily, size);

+0

作品!谢谢:) – imulsion

11

试试这个

newlabel.Font = new Font(newlabel.Font.FontFamily, Fontsize); 
+0

也是一个很好的答案,谢谢! – imulsion

3
Label newlabel = new Label(); 

newlabel.Font = new System.Drawing.Font(l.Font.FontFamily.Name, 12); 
1
var label1 = new Label(); 
label1.Font = new Font(new FontFamily(System.Drawing.Text.GenericFontFamilies.Serif), 10); 
1

首先,解释以下错误:

Property or indexer 'System.Drawing.Font.Size' cannot be assigned to -- it is read only

这是关于变量可访问性的编译时错误。在您的示例中,System.Drawing.Font.Size不能被修改,因为Font类中的属性被声明为public float Size { get; }。您可以通过右键单击“Size”并单击“转至定义”查看此功能。

上面显示的属性声明描述了一个名为Size的浮点值,它具有公共的'getter'方法 - 意味着您可以从该属性中检索值。
它没有'setter'属性,这使得修改不可能。

由于属性无法更改,因此您需要创建一个新的Font,将Font属性更改为new Font("Times New Roman", 12.0f);之类的内容。看看下面的MSDN documentation,它提供了Font类的所有不同的构造函数。

工作示例如下所示为您提供方便:

Label newlabel = new Label { 
    Text = "BOOM", 
    Font = new Font("Times New Roman", 12.0f), 
    ForeColor = Color.White, 
    Location = new Point(250, 250), 
    AutoSize = false 
}; 
this.Controls.Add(newlabel);