开发者

WPF/Silverlight: Find the name of a color

Is there a way to get the name of a color. The color is a System.Windows.Media.Color and the names I'm looking for are defined as properties on the System.Windows.Media.Colo开发者_如何学编程rs module.


Try this extension method:

static class ColorHelpers
{

    public static string GetColorName(this Color color)
    {
        return _knownColors
            .Where(kvp => kvp.Value.Equals(color))
            .Select(kvp => kvp.Key)
            .FirstOrDefault();
    }

    static readonly Dictionary<string, Color> _knownColors = GetKnownColors();

    static Dictionary<string, Color> GetKnownColors()
    {
        var colorProperties = typeof(Colors).GetProperties(BindingFlags.Static | BindingFlags.Public);
        return colorProperties
            .ToDictionary(
                p => p.Name,
                p => (Color)p.GetValue(null, null));
    }

Usage:

Color c = ...;
string name = c.GetColorName();

EDIT: this is roughly the same as Meleak's answer, but it should be faster since the reflection is only done once...


Modified answer from Thomas Levesque to populate the Dictionary only when 1st needed, instead of taking the cost at startup (going to use at speech recognition-driven turtle graphics, so that user can pronounce known color names to change the turtle's pen color)

//Project: SpeechTurtle (http://SpeechTurtle.codeplex.com)
//Filename: ColorUtils.cs
//Version: 20150901

using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Windows.Media;

namespace SpeechTurtle.Utils
{
  /// <summary>
  /// Color-related utility methods
  /// </summary>
  public static class ColorUtils //based on http://stackoverflow.com/questions/4475391/wpf-silverlight-find-the-name-of-a-color
  {
    #region --- Fields ---

    private static Dictionary<string, Color> knownColors; //=null

    #endregion

    #region --- Methods ---

    #region Extension methods

    public static string GetKnownColorName(this Color color)
    {
      return GetKnownColors()
          .Where(kvp => kvp.Value.Equals(color))
          .Select(kvp => kvp.Key)
          .FirstOrDefault();
    }

    public static Color GetKnownColor(this string name)
    {
      Color color;
      return GetKnownColors().TryGetValue(name, out color) ? color : Colors.Black; //if color for name is not found, return black
    }

    #endregion

    public static Dictionary<string, Color> GetKnownColors()
    {
      if (knownColors == null)
      {
        var colorProperties = typeof(Colors).GetProperties(BindingFlags.Static | BindingFlags.Public);
        knownColors = colorProperties.ToDictionary(
          p => p.Name,
          p => (Color)p.GetValue(null, null));
      }
      return knownColors;
    }

    public static string[] GetKnownColorNames()
    {
      return GetKnownColors().Keys.ToArray();
    }

    #endregion
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜