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:
Post a Comment