I search a way to save the color of a brush as a string. For example I have a Brush which has the color red. Now I want to write \"red\" in a textbox.
Thanks for any
What type of brush is this? If its drawing namespace, then brush is an abstract class.! For SolidBrush, do:
brush.Color.ToString()
Otherwise, get the color property and use ToString() method to convert color to its string representation.
If the Brush
was created using a Color
from System.Drawing.Color
, then you can use the Color
's Name property.
Otherwise, you could just try to look up the color using reflection
// hack
var b = new SolidBrush(System.Drawing.Color.FromArgb(255, 255, 235, 205));
var colorname = (from p in typeof(System.Drawing.Color).GetProperties()
where p.PropertyType.Equals(typeof(System.Drawing.Color))
let value = (System.Drawing.Color)p.GetValue(null, null)
where value.R == b.Color.R &&
value.G == b.Color.G &&
value.B == b.Color.B &&
value.A == b.Color.A
select p.Name).DefaultIfEmpty("unknown").First();
// colorname == "BlanchedAlmond"
or create a mapping yourself (and look the color up via a Dictionary
), probably using one of many color tables around.
Edit:
You wrote a comment saying you use System.Windows.Media.Color
, but you could still use System.Drawing.Color
to look up the name of the color.
var b = System.Windows.Media.Color.FromArgb(255, 255, 235, 205);
var colorname = (from p in typeof(System.Drawing.Color).GetProperties()
where p.PropertyType.Equals(typeof(System.Drawing.Color))
let value = (System.Drawing.Color)p.GetValue(null, null)
where value.R == b.R &&
value.G == b.G &&
value.B == b.B &&
value.A == b.A
select p.Name).DefaultIfEmpty("unknown").First();
Basically I'll post what was already answered.
string color = textBox1.Text;
// best, using Color's static method
Color red1 = Color.FromName(color);
// using a ColorConverter
TypeConverter tc1 = TypeDescriptor.GetConverter(typeof(Color)); // ..or..
TypeConverter tc2 = new ColorConverter();
Color red2 = (Color)tc.ConvertFromString(color);
// using Reflection on Color or Brush
Color red3 = (Color)typeof(Color).GetProperty(color).GetValue(null, null);
// in WPF you can use a BrushConverter
SolidColorBrush redBrush = (SolidColorBrush)new BrushConverter().ConvertFromString(color);
Original answer: Convert string to Brushes/Brush color name in C#