I ran into this problem last night when I was preparing a bigger demo for my blog. It took me some time to find a solution for a simple but important piece. I decided to go ahead an break the demo down into smaller pieces.
The problem is simple: How to get a Color Object from a String of Text (e.g. AliceBlue, Blanched Almond, or just Blue)
At the Silverlight Forum I found a good link which I used as a base:
http://silverlight.net/forums/p/9134/28837.aspx
Here is my modified snippet:
private 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);
if (color != null)
{
return (Color)color;
}
throw new InvalidCastException("Color not defined");
}
I decided to throw an InvalidCastException so I can process the Exception later on. Of course this also could be the place to return a default Color right now. I just like to keep it more flexible.
To be able to use it as a Converter Parameter in UI Bindinding, I wrapped it into a ColorConverter:
public class ColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value.GetType() == typeof(String))
{
try
{
Color c = getColorFromString(value as string);
return new SolidColorBrush(c);
}
catch (InvalidCastException ex)
{
return null;
}
}
return null;
}
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
I decided here to return null in case something goes wrong. In this case the binding Framework Element has the chance to use an attached Property form its parent.
Let me know if you have an issus with it or if you have a suggestion to make the code better. Feedback is always highly welcome.
Next time I will present the rest of the demo with a full blown solution. So stay tuned in.
Tom
P.S.: Is there a tool to format the codesnippets automatically?