Archive
HowTo: List all known color names and find name of given color at WPF
This is my answer at
http://stackoverflow.com/questions/4475391/wpf-silverlight-find-the-name-of-a-color
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
- }
- }
HowTo: Call C# method from class that has same name as namespace
In the C# compiler error case shown above, CaptionsGrid class exists in namespace ClipFlair.CaptionsGrid so in the code we have “using ClipFlair.CaptionsGrid;” at the top of the file where we want to call the “SaveAudio” static method of CaptionsGrid class.
But then we get the error “The type or namespace name ‘…’ does not exist in the namespace ‘…’ (are you missing an assembly reference?)”
The solution is to use a more full identifier, that is use “CaptionsGrid.CaptionsGrid.SaveAudio(…)” or even use the full namespace path “ClipFlair.CaptionsGrid.CaptionsGrid.SaveAudio(…)”. In the last case you wouldn’t need the “using ClipFlair.CaptionsGrid” at all.
It is better to avoid naming the parent namespace part of a class with the same name as the class, but some times one can’t find a better name I guess.