简体   繁体   English

在代码 C# 中将 Label 字体更改为粗体

[英]Changing a Label font to bold in code C#

I searched for this for A while but I couldn't find the answer, so I hope it's not a duplicate.我搜索了一段时间,但找不到答案,所以我希望它不是重复的。

I have the following code:我有以下代码:

this.Controls.Add(new Label { Location = new Point(10, 10), 
                              AutoSize = true, 
                              Name = "jobNumStatic",
                              Text = "Job Number:", 
                              Font = new Font(jobNumStatic.Font, FontStyle.Bold) });

I'm trying to change the font to bold.我正在尝试将字体更改为粗体。 But that code gives the error, The name 'jobNumStatic' does not exist in the current context.但是该代码给出了错误,名称“jobNumStatic”在当前上下文中不存在。 Is there any way to make the font bold here?有什么办法可以让这里的字体变粗吗?

I also tried:我也试过:

jobNumStatic.Font = new Font(jobNumStatic.Font, FontStyle.Bold) });

After declaring the Label, and it gives me the same error.在声明 Label 之后,它给了我同样的错误。

To use a Label 's default font as prototype just use the static Label.DefaultFont property: 要将Label的默认字体用作原型,只需使用静态Label.DefaultFont属性:

this.Controls.Add(new Label { Location = new Point(10, 10), 
                          AutoSize = true, 
                          Name = "jobNumStatic",
                          Text = "Job Number:", 
                          Font = new Font(Label.DefaultFont, FontStyle.Bold) });

jobNumStatic is not a variable in your scope. jobNumStatic在您的范围内不是变量。 You provide the string "jobNumStatic" at runtime for the Name property of the newly created Label , but that does not mean you magically have a variable with that name at compile-time . 您在运行时为新创建的LabelName属性提供了字符串"jobNumStatic" ,但这并不意味着您在编译时就拥有了一个具有该名称的变量。

If you need to access this Label later you may of course declare a member variable: 如果以后需要访问此Label ,则可以声明一个成员变量:

private Label jobNumStatic;

and assign the created instance to that variable: 并将创建的实例分配给该变量:

jobNumStatic = new Label { Location = new Point(10, 10), 
                          AutoSize = true, 
                          Name = "jobNumStatic",
                          Text = "Job Number:", 
                          Font = new Font(Label.DefaultFont, FontStyle.Bold) });
this.Controls.Add(jobNumStatic);

Simply use the code below:只需使用以下代码:

Label1.Font = new Font(Font, Size, FontStyle.Bold);

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

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