Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to Brushes/Brush color name in 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"/> 

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

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

like image 401
Clinton Pierce Avatar asked Dec 16 '08 21:12

Clinton Pierce


2 Answers

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"); 
like image 63
Lucas Avatar answered Oct 06 '22 03:10

Lucas


String to brush:

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

That's my case here!

like image 22
Junior Mayhé Avatar answered Oct 06 '22 02:10

Junior Mayhé