C# 更改字符串颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17053359/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:28:43  来源:igfitidea点击:

Change string color

c#winforms

提问by user2214609

I have label that contain of several strings and one of those string i want to change it color.

我有包含多个字符串和其中一个字符串的标签,我想更改它的颜色。

This is what i have try:

这是我尝试过的:

private string state = string.Empty;
state = System.Drawing.Color.Blue.ToString();

But it still remained to same color

但它仍然保持相同的颜色

回答by rocky

Label cannot contain items of more than one color. Use more labels or some other kind of control. But from the code you pasted I recommend to go through some .NET tutorial. You probably miss the basic concepts.

标签不能包含多于一种颜色的项目。使用更多标签或其他类型的控件。但是根据您粘贴的代码,我建议您阅读一些 .NET 教程。您可能错过了基本概念。

回答by Jon Skeet

As far as I'm aware, a Windows Forms Labelcan only use a single color for the whole of its text. If you want multi-colored text, you'll either need to use multiple labels or use RichTextBox... or perform the painting yourself, of course.

据我所知,Windows 窗体Label只能为其整个文本使用一种颜色。如果你想要多色文本,你要么需要使用多个标签,要么使用RichTextBox......当然,或者自己进行绘画。

回答by xen-0

You have to change the colour of the label, not the string.

您必须更改标签的颜色,而不是字符串。

So you'd have a label on your form, say LabelTest, then in your code would look like this:

所以你的表单上会有一个标签,比如LabelTest,然后在你的代码中看起来像这样:

string state = "Some text for our label";
LabelTest.Text = state;
LabelTest.ForeColor = System.Drawing.Color.Blue;

As has been mentioned in other answers, to use multiple colours, you'd need multiple labels, each with their text and colour set separately.

正如其他答案中提到的,要使用多种颜色,您需要多个标签,每个标签的文本和颜色分别设置。

回答by Piatoz LP

//this is for label color

//这是标签颜色

Label1.Text.ForeColor = System.Drawing.Color.Red;

//this for textenter code here

//这是文本enter code here

Label1.Text.ForeColor = System.Drawing.Color.Red;