Wednesday, January 30, 2008

Converting String in to color at run time and assiging it to Silverlight's TextBlock's foreground

Today I m very happy that I found very interesting thing after exploring msdn, I had a task that required to change color of textBlock’s font at run time. it is easy when working in .net related things, Normally, we used to convert the string to known-color by using TypeDescriptor. Unfortunately, I'm not able to use it in Silver light project,

we can do this

Text1.Foreground = new SolidColorBrush (Color.FromRgb (22, 54, 55));

Works fine. But Problem arises when u want to change color on run time and getiing color name in string format.like

String colorToApply=”Red”;
Text1.Foreground = new SolidColorBrush (xxxx);

I was looking too much for TypeDescriptor and ColorConverter. But when exploring, I found System.Reflection class that will help me to achieve that task
So here is what i did, I made a separate class in my project


using System.Reflection;
public class ColorConvertor
{
public Color GetThisColor(string colorString)
{

Type colorType = (typeof(System.Windows.Media.Colors));
if (colorType.GetProperty(colorString) != null)
{

object o = colorType.InvokeMember(colorString, BindingFlags.GetProperty, null,null,null);

if (o != null)
{
return (Color)o;
}
}
return Colors.Black;// If unknown color, return black
}
}
}

And I m using that calss like that,

ColorReflector cr = new Ravs.ColorReflector();
string colorToApply="Yellow";
Text1.Foreground = new SolidColorBrush(cr.GetThisColor(colorToApply));

Well, normally we don't look at the Reflection,but now i believe it is the most powerful Namespace(at least in my case)

Many thanks to Nash, Michael Sync ,Ravi Kant and U



No comments: