WinRT 中似乎缺少 ColorConverter,但稍加思考就可以轻松编写自己的。在下面的示例中,我创建了一些扩展方法,可以编写如下代码:
Color red = "Red".ConvertToColor(); or
Color color = colorName.ConvertToColor();
和
Background = colorName.CreateColorBrush();
为 WinRT 和 WPF 编译的扩展实现:
#if NETFX_CORE
using Windows.UI;
using Windows.UI.Xaml.Media;
#else
using System.Windows.Media;
#endif
using System;
using System.Globalization;
using System.Reflection;
namespace YourNiceExtensionsNamespace
{
/// <summary>
/// Extension to convert a string color name like "Red", "red" or "RED" into a Color.
/// Using ColorsConverter instead of ColorConverter as class name to prevent conflicts with
/// the WPF System.Windows.Media.ColorConverter.
/// </summary>
public static class ColorsConverter
{
/// <summary>
/// Convert a string color name like "Red", "red" or "RED" into a Color.
/// </summary>
public static Color ConvertToColor(this string colorName)
{
if (string.IsNullOrEmpty(colorName)) throw new ArgumentNullException("colorName");
MethodBase getColorMethod = FindGetColorMethod(colorName);
if (getColorMethod == null)
{
// Using FormatException like the WPF System.Windows.Media.ColorConverter
throw new FormatException(string.Format(CultureInfo.InvariantCulture, "Color name {0} not found in {1}",
colorName, typeof(Colors).FullName));
}
return (Color)getColorMethod.Invoke(null, null);
}
/// <summary>
/// Create a SolidColorBrush from a color name
/// </summary>
public static Brush CreateColorBrush(this string colorName)
{
if (string.IsNullOrEmpty(colorName)) throw new ArgumentNullException("colorName");
Color color = colorName.ConvertToColor();
return new SolidColorBrush(color);
}
/// <summary>
/// Verify if a string color name like "Red", "red" or "RED" is a known color in the static Colors class
/// </summary>
public static bool IsColorName(this string colorName)
{
if (string.IsNullOrEmpty(colorName)) throw new ArgumentNullException("colorName");
return FindGetColorMethod(colorName) != null;
}
private static MethodBase FindGetColorMethod(string colorName)
{
foreach (PropertyInfo propertyInfo in typeof(Colors).GetTypeInfo().DeclaredProperties)
{
if (propertyInfo.Name.Equals(colorName, StringComparison.OrdinalIgnoreCase))
{
MethodBase getMethod = propertyInfo.GetMethod;
if (getMethod.IsPublic && getMethod.IsStatic)
return getMethod;
break;
}
}
return null;
}
}
}