2010-10-19 73 views
5

我有这样的代码。C#将颜色应用于字体

System.Drawing.Color col = System.Drawing.ColorTranslator.FromHtml("#101B83"); 
System.Drawing.Font nameFont = new System.Drawing.Font("Tahoma", 10); 
System.Drawing.Font birthdayFont = new System.Drawing.Font("Tahoma", 6); 
System.Drawing.SolidBrush drawBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Black); 
nameFont.Color = col; 

最后一行不起作用,因为无法找到.Color字段。为什么?

+0

你有没有听说过'namespaces'? – Mike 2010-10-19 09:00:07

回答

12

因为字体没有颜色。控件可以使用字体和颜色来呈现文本,但颜色不是字体的属性。

编辑:

如果你想使用给定的字体和颜色,你可以做以下的文本框(我假设你正在使用的WinForms):

var myTextBox = new TextBox(); 
myTextBox.ForeColor = col; 
myTextBox.Font = birthdayFont; 
myTextBox.Text = "Happy birthday!"; 

this.Controls.Add(myTextBox); 
+0

我见过在教程上使用颜色的例子...好的..如何用控件做到这一点? – 2010-10-19 08:32:28

+0

@Toktik我已经更新了我的答案。 – 2010-10-19 08:40:29

2

字体做没有颜色。您在绘图代码本身中使用颜色,或者使用Control.ForeColor属性

1

将颜色设置为控件的ForeColor属性。这将设置您的字体所需的颜色。 您不能直接将颜色设置为字体。 你将不得不分别设置字体和forecolor控制。