Windows Phone(或 Silverlight)中没有 System.Windows.Media.ColorConverter,所以我需要另一种方法来获取包含颜色名称的字符串,例如“红色”并从中生成一个 Color 对象。
我发现了这种可能性,但它不起作用,因为 colorType.GetProperty 总是返回 null。
public static Color ConvertFromString(string colorString)
{
Color retval = Colors.Transparent;
Type colorType = (typeof(Colors));
if (colorType.GetProperty(colorString) != null)
{
object o = colorType.InvokeMember(colorString,
BindingFlags.GetProperty, null, null, null);
if (o != null)
{
retval = (Color)o;
}
}
return retval;
}
有什么想法吗?
请您参考如下方法:
试试这个:
public static Color GetColor(String ColorName)
{
Type colors = typeof(System.Windows.Media.Colors);
foreach(var prop in colors.GetProperties())
{
if(prop.Name == ColorName)
return ((System.Windows.Media.Color)prop.GetValue(null, null));
}
throw new Exception("No color found");
}
