smarble
smarble

Reputation: 335

Getting SolidColorBrush from a string

I'm trying to set the foreground of a textblock on the backend using a string ( something like "Red")

I've tried this:

ColorText.Foreground = new BrushConverter().ConvertFromString(colors[color2].ToString());

However, it doesn't seem to be recognizing BrushConvert(). I've included System.Windows.Media but it still can't be found.

Is there another way to go about doing this?

Upvotes: 0

Views: 1360

Answers (1)

Alaa Masoud
Alaa Masoud

Reputation: 7135

BrushConverter isn't available in windows phone. You could build up a dictionary of colors then pass the color you want to SolidColorBrush ctor with a helper method.

public static class ColorsHelper {
  private static readonly Dictionary<string, Color> dict =
        typeof(Colors).GetProperties(BindingFlags.Public | BindingFlags.Static)
        .Where(prop => prop.PropertyType == typeof(Color))
        .ToDictionary(prop => prop.Name, prop => (Color)prop.GetValue(null, null));

  public static Color FromName(string name) {
    return dict[name];
  }
}

ColorText.Foreground = new SolidColorBrush(ColorsHelper.FromName("Red"));

Make sure the above dictionary uses System.Windows.Media.Color struct and System.Windows.Media.Colors class. I believe there are a few Color types around so type in the whole namespace if necessary or rename it.

Upvotes: 1

Related Questions