C#의 브러시/브러시 색상 이름으로 문자열을 변환합니다.
문제
개발자가 문자열을 전달하여 텍스트 색상을 지정할 수있는 구성 파일이 있습니다.
<text value="Hello, World" color="Red"/>
거대한 스위치 명령문이있는 대신 가능한 모든 색상을 찾는 대신 클래스 시스템에서 속성을 사용하는 것이 좋을 것입니다.
Brush color = Brushes.Black; // Default
// later on...
this.color = (Brush)Enum.Parse(typeof(Brush), prasedValue("color"));
브러시/브러시의 값이 열거되지 않는 것을 제외하고. 그래서 enum.parse는 나에게 기쁨을주지 않습니다. 제안?
해결책
모든 이전 답변의 요약, 문자열을 색상이나 브러시로 변환하는 다른 방법 :
// 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");
다른 팁
브러시 끈 :
myTextBlock.Foreground = new BrushConverter().ConvertFromString("#FFFFFF") as SolidColorBrush;
그게 내 사건이야!
브러시는 이렇게 선언 할 수 있습니다
Brush myBrush = new SolidBrush(Color.FromName("Red"));
오. 잠시 후 나는 찾았다 :
Color.FromName(a.Value)
"Post"를 누른 후. 거기에서 그것은 다음과 같은 짧은 단계입니다.
color = new SolidBrush(Color.FromName(a.Value));
다른 사람들을 위해이 질문을 여기에 남겨 두겠습니다 ....
이를 위해 반사를 사용할 수 있습니다.
Type t = typeof(Brushes);
Brush b = (Brush)t.GetProperty("Red").GetValue(null, null);
물론 문자열이 잘못되었는지 여부 처리/범위 확인을 원할 것입니다.
타이프 콘버터를 사용하는 것이 가장 좋은 방법이라는 데 동의합니다.
Color c = (Color)TypeDescriptor.GetConverter(typeof(Color)).ConvertFromString("Red");
return new Brush(c);
a를 사용해보십시오 TypeConverter
. 예시:
var tc = TypeDescriptor.GetConverter(typeof(Brush));
또 다른 대안은 반사를 사용하고 속성을 살펴 보는 것입니다. SystemBrushes
.
원한다면 더 많이 확장하여 R, G 및 B 값에 대한 값을 지정할 수 있습니다. 그런 다음 COLOR.FROMARGB (int r, int g, int b)를 호출합니다.
당신이 사용할 수있는 System.Drawing.KnownColor 열거적. 알려진 모든 시스템 색상을 지정합니다.
제휴하지 않습니다 StackOverflow