Beispiel #1
0
        /// <summary>
        /// This function tries to convert a given string into a Color in the following order:
        ///    1. If the string starts with '#' the function tries to get the color from the hex-code
        ///    2. else the function tries to find the color in the color names Dictionary
        ///    3. If 1. + 2. were not successfull the function adds a '#' sign and tries 1. + 2. again
        /// </summary>
        /// <param name="ColorName">The localized name of the color, the hex-code of the color or the internal colorname</param>
        /// <returns>the Color if successfull, else null</returns>
        public static Color?ColorFromString(string ColorName, Dictionary <Color, string> colorNamesDictionary = null)
        {
            Color?result = null;

            try
            {
                // if we don't have a string, we cannot have any Color
                if (string.IsNullOrWhiteSpace(ColorName))
                {
                    return(null);
                }

                if (!ColorName.StartsWith("#", StringComparison.Ordinal))
                {
                    result = ColorNamesDictionary.FirstOrDefault(x => string.Equals(x.Value, ColorName, StringComparison.OrdinalIgnoreCase)).Key as Color?;
                }
                if (!result.HasValue)
                {
                    result = ColorConverter.ConvertFromString(ColorName) as Color?;
                }
            }
            catch (FormatException)
            {
                if (!result.HasValue && !ColorName.StartsWith("#", StringComparison.Ordinal))
                {
                    result = ColorFromString("#" + ColorName);
                }
            }

            return(result);
        }
 public void SetUp()
 {
     _dictionary = new ColorNamesDictionary();
 }