How to specify color in configuration

How can I specify a color in app.config and then convert it to the actual System.Drawing.Color object at runtime?

+3
source share
6 answers

One way would be to specify one of the KnownColor values as the configuration text, and then use Color.FromName to create a Color object.

+3
source

Color- this is strange; regular xml serialization usually doesn't work - so you often need to add your own code, perhaps via TypeConverter:

static void Main()
{

    Test(Color.Red);
    Test(Color.FromArgb(34,125,75));
}
static void Test(Color color)
{
    TypeConverter converter = TypeDescriptor.GetConverter(typeof(Color));
    string s = converter.ConvertToInvariantString(color);
    Console.WriteLine("String: " + s);
    Color c = (Color) converter.ConvertFromInvariantString(s);
    Console.WriteLine("Color: " + c);
    Console.WriteLine("Are equal: " + (c == color));
}

Outputs:

String: Red
Color: Color [Red]
Are equal: True
String: 34, 125, 75
Color: Color [A=255, R=34, G=125, B=75]
Are equal: True
+2
source

:

<add key="SomethingsColor" value="Black" />

:

Color myColor = Color.FromName(ConfigurationManager.AppSettings["KEY"]);
+2

ColorTranslator. , appSettings, ColorTranslator, . , .FromHtml() .

+2

ASP.NET... ( ) "app.config" ( -). , , .

0

int, , color, toArgb argb .

.

private ColorInt

public Color shapeColor
{
    get {
         return Color.FromArgb(ColorInt);
     }
      set 
    {
        ColorInt = value.toargb()
    }
}
0

Source: https://habr.com/ru/post/1699043/


All Articles