如何以编程方式设置 TextBlock 前景色十六进制颜色 [英] How to programmatically set TextBlock Foreground Hex Color
问题描述
我必须实用地使用文本块的前景色十六进制颜色.它不起作用.请帮助我.
I have to use Foreground Hex color of a Textblock Pragmatically.it does not work.Please help me.
我试过这个例子
txtHome.Foreground = new SolidColorBrush(Colors.Red);
但我想使用十六进制颜色代码而不是使用 Color.red 等.
but I want use Hex color code not use Color.red etc..
推荐答案
虽然有些答案会创建不必要的字符串,但我建议只使用最有效的:
While there are answers that create unnecessary strings, I'd suggest just using the most efficient:
var brush=new SolidColorBrush(Color.FromArgb(0xFF, 0xD0, 0x20, 0x30));
我刚刚使用了 FromArgb
方法直接转换颜色的十六进制表示.第一个参数是 alpha 或不透明度,您始终可以使用 255/0xFF 来指定完全不透明度.然后,它只提供表示颜色的 3 个字节,它们的顺序与它们出现在颜色的常见十六进制表示中的顺序相同.在上面的例子中:"D02030"
.
此外,您可以考虑创建一个表示 SolidColorBrush
的可重用资源,并将其添加到 app.xaml
文件中,使其成为全球可用的:
Also, you might consider creating a reusable resource representing the SolidColorBrush
and adding it to the app.xaml
file so it becomes globally available:
<SolidColorBrush x:Key="myBrush" Color="#D02030" />
然后,在代码中:
txtHome.Foreground = App.Current.Resources["myBrush"] as SolidColorBrush;
这篇关于如何以编程方式设置 TextBlock 前景色十六进制颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!