Question

I'm using Windows Phone. The problem is that it doesn't have the Color.FromName instead it has the Color.FromArgb.

I have a rectangle and I want to set its fill color depending on what the color is from a file that is being read. e.g. I've saved "Red" in a file called colors. I read that and I send it to a string called LpColor now that will hold the text "Red" inside.

Now how do I use LpColor in Rectangle.Fill = .... Doing Rectangle.Fill = LpColor will not work.

This is the code on how I read my file:

IsolatedStorageFileStream readColor = store.OpenFile("/contactColor.txt", FileMode.Open, FileAccess.Read);
using (StreamReader contactColor = new StreamReader(readColor))
{
  var color = contactColor.ReadToEnd();
  LpColor = color;
}
Was it helpful?

Solution

If you must save it as a string (Red), you can write a converter method which will convert the string back to a color. Depending on how many colors you have, the complexity of the method will grow, so you might want to rethink saving the color as name - maybe you could save it as a combination of ARGB and name? Use a class to hold that info? There are many many options.

Anyway, your simple converter would do something like this:

private SolidColorBrush ColorNameToBrush(string colorName)
{
    Color color = Color.FromArgb(0,0,0,0);
    if (colorName == "Red")
    {
        color = new Color() { R = 255, G = 0, B = 0};
    }
    else if ...
    {

    }

    return new SolidColorBrush(color);
}

Using switch statement instead of endless if-else-if might be a better idea if you have a lot of strings, though.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top