Convert string to Brushes/Brush color name in C#

橙三吉。 提交于 2019-11-27 03:54:04

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");

String to brush:

myTextBlock.Foreground = new BrushConverter().ConvertFromString("#FFFFFF") as SolidColorBrush;

That's my case here!

A brush can be declared like this

Brush myBrush = new SolidBrush(Color.FromName("Red"));

D'oh. After a while of looking I found:

 Color.FromName(a.Value)

After hitting "post". From there it's a short step to:

 color = new SolidBrush(Color.FromName(a.Value));

I'll leave this question here for others....

You could use reflection for this:

Type t = typeof(Brushes);
Brush b = (Brush)t.GetProperty("Red").GetValue(null, null);

Of course, you'll want some error handling/range checking if the string is wrong.

I agree that using TypeConverters are the best method:

 Color c = (Color)TypeDescriptor.GetConverter(typeof(Color)).ConvertFromString("Red");
 return new Brush(c);

Try using a TypeConverter. Example:

var tc = TypeDescriptor.GetConverter(typeof(Brush));

Another alternative is to use reflection, and go over the properties in SystemBrushes.

If you want, you can extend this even more and allow them to specify values for the R, G and B values. Then you just call Color.FromArgb(int r, int g, int b);

You can use System.Drawing.KnownColor enum. It specifies all known system colors.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!