//http://aspascension.codeplex.com/ //Microsoft Public License (Ms-PL) using System; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using System.Reflection; using System.Windows.Data; namespace ASPAscension.Silverlight.Converters { public class ColorConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (value.GetType() == typeof(String)) { string val = value as string; Color c; if (val.StartsWith("#")) { val = val.Replace("#", ""); byte a = System.Convert.ToByte("ff", 16); byte pos = 0; if (val.Length == 8) { a = System.Convert.ToByte(val.Substring(pos, 2), 16); pos = 2; } byte r = System.Convert.ToByte(val.Substring(pos, 2), 16); pos += 2; byte g = System.Convert.ToByte(val.Substring(pos, 2), 16); pos += 2; byte b = System.Convert.ToByte(val.Substring(pos, 2), 16); c = Color.FromArgb(a, r, g, b); return new SolidColorBrush(c); } else { try { c = GetColorFromString(value as string); return new SolidColorBrush(c); } catch (InvalidCastException ex) { return null; } } } return null; } public static Color GetColorFromString(string colorString) { Type colorType = (typeof(System.Windows.Media.Colors)); if (colorType.GetProperty(colorString) != null) { object color = colorType.InvokeMember(colorString, BindingFlags.GetProperty, null, null, null); try { return (Color)color; } catch { throw new InvalidCastException("Color not defined"); } } return Colors.Transparent; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { SolidColorBrush val = value as SolidColorBrush; return val.Color.ToString(); //if (typeof(Colors).GetProperty(val.Color.ToString()) != null) // return typeof(Colors).GetProperty(val.Color.ToString()).GetValue(val, null); //else // return "#" + val.Color.A.ToString() + val.Color.R.ToString() + val.Color.G.ToString() + val.Color.B.ToString(); } } }