简体   繁体   中英

How to get the Color Name String of Color in c# windows application

I'm working on some color shades for that I have created some custom properties of colors like this..

public struct StaticColors
    {
        //White Shades
        public static Color White = ColorTranslator.FromHtml("#ecf0f1");
        public static Color White_1 = ColorTranslator.FromHtml("#c5d1d4");
        public static Color White_2 = ColorTranslator.FromHtml("#a8babf");

        //Red Shades
        public static Color Red = ColorTranslator.FromHtml("#db2828");
        public static Color Red_1 = ColorTranslator.FromHtml("#a41b1b");
        public static Color Red_2 = ColorTranslator.FromHtml("#781414");
    }

Now I want the string of any color...

var ColorName = StaticColors.White.ToString() 

then I need "White" in ColorName varibale so I can concatenate with others but I'm getting a string form of RGBA values.

any one can help me please to convert Color into string?

One way to do this is to use the nameof expression, which returns the string name of the member:

 var ColorName = nameof(StaticColors.White);

Another way to accomplish this, if you want Name to be a property of the field, is to wrap the Color class in your own custom struct and give it a Name property:

public struct StaticColor
{
    public string Name { get; }
    public Color Color { get; }

    public StaticColor(string name, Color color)
    {
        Name = name;
        Color = color;
    }
}

Then in your StaticColors struct, you can have fields of this type instead of Color :

public struct StaticColors
{
    //White Shades
    public static StaticColor White = 
        new StaticColor("White", ColorTranslator.FromHtml("#ecf0f1"));
    public static StaticColor White_1 = 
        new StaticColor("White_1", ColorTranslator.FromHtml("#c5d1d4"));
    public static StaticColor White_2 = 
        new StaticColor("White_2", ColorTranslator.FromHtml("#a8babf"));

    //Red Shades
    public static StaticColor Red = 
        new StaticColor("Red", ColorTranslator.FromHtml("#db2828"));
    public static StaticColor Red_1 = 
        new StaticColor("Red_1", ColorTranslator.FromHtml("#a41b1b"));
    public static StaticColor Red_2 = 
        new StaticColor("Red_2", ColorTranslator.FromHtml("#781414"));
}

And now you can access the Color or the Name of any of the properties:

var colorName = StaticColors.White.Name;
var colorColor = StaticColors.White.Color;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM