Wednesday, April 30, 2008

Color / SolidColorBrush object from color name in silverlight

The situation lead to this post was one of my friend's query.He just wants to set Background of something with a Color name in hand.
Basically string "Green" should be converted into Color object.
It seems like a silly thing as we have enough experience in .net.(I assume that persons wont jump into silverlight without basic skills in .net or jscript).But this becomes complicated when we are not able find out the method 'Color.FromName()'.
We were not able to find out a direct method which meets his requirement.But at last we arrived on the following.

private void Button_Click(object sender, RoutedEventArgs e) { 
string s = "<solidcolorbrush> xmlns=''";

s+=" xmlns:x=''" ;

s+=" Color='Green'/>";

SolidColorBrush brush =(SolidColorBrush) XamlReader.Load(s);

LayoutRoot.Background = brush;


It is nothing but creating a SolidColorBrush object from xaml where he can insert the color name in string.