将字符串转换为画笔/画笔颜色名称在C# [英] Convert string to Brushes/Brush color name in C#

查看:358
本文介绍了将字符串转换为画笔/画笔颜色名称在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个配置文件,其中开发人员可以传递一个字符串指定文本颜色:

I have a configuration file where a developer can specify a text color by passing in a string:

 <text value="Hello, World" color="Red"/>

而不是有一个巨大的switch语句寻找所有可能的颜色,它会是不错的,只是使用的属性在类System.Drawing.Brushes,而不是让国内我可以这样说:

Rather than have a gigantic switch statement look for all of the possible colors, it'd be nice to just use the properties in the class System.Drawing.Brushes instead so internally I can say something like:

 Brush color = Brushes.Black;   // Default

 // later on...
 this.color = (Brush)Enum.Parse(typeof(Brush), prasedValue("color"));

除了在刷/无刷值不枚举。所以Enum.Parse没有给我快乐。建议?

Except that the values in Brush/Brushes aren't enums. So Enum.Parse gives me no joy. Suggestions?

推荐答案

回顾所有previous的答案,不同的方法将字符串转换为彩色或刷:

Recap of all previous answers, different ways to convert a string to a Color or Brush:

// best, using Color's static method
Color red1 = Color.FromName("Red");

// using a ColorConverter
TypeConverter tc1 = TypeDescriptor.GetConverter(typeof(Color)); // ..or..
TypeConverter tc2 = new ColorConverter();
Color red2 = (Color)tc.ConvertFromString("Red");

// using Reflection on Color or Brush
Color red3 = (Color)typeof(Color).GetProperty("Red").GetValue(null, null);

// in WPF you can use a BrushConverter
SolidColorBrush redBrush = (SolidColorBrush)new BrushConverter().ConvertFromString("Red");

这篇关于将字符串转换为画笔/画笔颜色名称在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆