代码之家  ›  专栏  ›  技术社区  ›  Clinton Pierce

将字符串转换为C中的画笔/画笔颜色名称#

  •  33
  • Clinton Pierce  · 技术社区  · 17 年前

    我有一个配置文件,开发人员可以在其中通过传递字符串指定文本颜色:

     <text value="Hello, World" color="Red"/>
    

    与其让一个巨大的switch语句查找所有可能的颜色,不如使用类System.Drawing.Brushes中的属性,这样我就可以在内部说:

     Brush color = Brushes.Black;   // Default
    
     // later on...
     this.color = (Brush)Enum.Parse(typeof(Brush), prasedValue("color"));
    

    除了画笔/画笔中的值不是枚举。所以num.parse没有给我带来快乐。建议?

    9 回复  |  直到 7 年前
        1
  •  67
  •   Lucas    17 年前

    回顾所有以前的答案,将字符串转换为颜色或画笔的不同方法:

    // best, using Color's static method
    Color red1 = Color.FromName("Red");
    
    // using a ColorConverter
    TypeConverter tc1 = TypeDescriptor.GetConverter(typeof(Color)); // ..or..
    TypeConverter tc2 = new ColorConverter();
    Color red2 = (Color)tc.ConvertFromString("Red");
    
    // using Reflection on Color or Brush
    Color red3 = (Color)typeof(Color).GetProperty("Red").GetValue(null, null);
    
    // in WPF you can use a BrushConverter
    SolidColorBrush redBrush = (SolidColorBrush)new BrushConverter().ConvertFromString("Red");
    
        2
  •  41
  •   Junior Mayhé    17 年前

    要刷的字符串:

    myTextBlock.Foreground = new BrushConverter().ConvertFromString("#FFFFFF") as SolidColorBrush;
    

    这是我的情况!

        3
  •  9
  •   WhatsThePoint    7 年前

    刷子可以这样声明

    Brush myBrush = new SolidBrush(Color.FromName("Red"));
    
        4
  •  7
  •   Clinton Pierce    17 年前

    哦。看了一会儿,我发现:

     Color.FromName(a.Value)
    

    点击“post”后。从这一步到:

     color = new SolidBrush(Color.FromName(a.Value));
    

    我将把这个问题留给其他人……

        5
  •  2
  •   Jon B    17 年前

    您可以使用反射:

    Type t = typeof(Brushes);
    Brush b = (Brush)t.GetProperty("Red").GetValue(null, null);
    

    当然,如果字符串错误,您需要一些错误处理/范围检查。

        6
  •  1
  •   Brian Rudolph    17 年前

    我同意使用类型转换器是最好的方法:

     Color c = (Color)TypeDescriptor.GetConverter(typeof(Color)).ConvertFromString("Red");
     return new Brush(c);
    
        7
  •  0
  •   leppie    17 年前

    尝试使用 TypeConverter . 例子:

    var tc = TypeDescriptor.GetConverter(typeof(Brush));
    

    另一种选择是使用反射,并在 SystemBrushes .

        8
  •  0
  •   BFree    17 年前

    如果您愿意,可以进一步扩展它,并允许它们为r、g和b值指定值。然后你就叫color.fromargb(int r,int g,int b);

        9
  •  -1
  •   Const Mi    9 年前

    你可以使用 System.Drawing.KnownColor 枚举。它指定所有已知的系统颜色。