code_junkie

Convert string to Brushes/Brush name in C#

Nov 13th, 2011
862
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.10 KB | None | 0 0
  1. <text value="Hello, World" color="Red"/>
  2.  
  3. Brush color = Brushes.Black; // Default
  4.  
  5. // later on...
  6. this.color = (Brush)Enum.Parse(typeof(Brush), prasedValue("color"));
  7.  
  8. // best, using Color's static method
  9. Color red1 = Color.FromName("Red");
  10.  
  11. // using a ColorConverter
  12. TypeConverter tc1 = TypeDescriptor.GetConverter(typeof(Color)); // ..or..
  13. TypeConverter tc2 = new ColorConverter();
  14. Color red2 = (Color)tc.ConvertFromString("Red");
  15.  
  16. // using Reflection on Color or Brush
  17. Color red3 = (Color)typeof(Color).GetProperty("Red").GetValue(null, null);
  18.  
  19. // in WPF you can use a BrushConverter
  20. SolidColorBrush redBrush = (SolidColorBrush)new BrushConverter().ConvertFromString("Red");
  21.  
  22. Color.FromName(a.Value)
  23.  
  24. color = new SolidBrush(Color.FromName(a.Value));
  25.  
  26. myTextBlock.Foreground = new BrushConverter().ConvertFromString("#FFFFFF") as SolidColorBrush;
  27.  
  28. Type t = typeof(Brushes);
  29. Brush b = (Brush)t.GetProperty("Red").GetValue(null, null);
  30.  
  31. var tc = TypeDescriptor.GetConverter(typeof(Brush));
  32.  
  33. Color c = (Color)TypeDescriptor.GetConverter(typeof(Color)).ConvertFromString("Red");
  34. return new Brush(c);
Add Comment
Please, Sign In to add comment