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='http://schemas.microsoft.com/client/2007'";

s+=" xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'" ;

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.

5 comments:

JC said...

Nice hack!

Joymon said...

Thanks...
You are always welcome to share your hacks with me :-)

Jordi said...

it's just what I needed!

Unknown said...

Thanks...

Niranjan said...

Very useful tip