Getting SolidColorBrush from a string

后端 未结 1 1154
梦谈多话
梦谈多话 2021-01-27 05:21

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 Bru         


        
1条回答
  •  一生所求
    2021-01-27 06:02

    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 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.

    0 讨论(0)
提交回复
热议问题