2012-04-08 9 views
90

Ich möchte SolidColorBrush von Hex-Wert wie #ffaacc erstellen. Wie kann ich das machen?Erstellen SolidColorBrush von Hex-Farbwert

auf MSDN, ich habe:

SolidColorBrush mySolidColorBrush = new SolidColorBrush(); 
mySolidColorBrush.Color = Color.FromArgb(255, 0, 0, 255); 

Also schrieb ich (unter Berücksichtigung meiner Methode Farbe wie #ffaacc erhält):

Color.FromRgb(
    Convert.ToInt32(color.Substring(1, 2), 16), 
    Convert.ToInt32(color.Substring(3, 2), 16), 
    Convert.ToInt32(color.Substring(5, 2), 16)); 

Aber dies gab Fehler als

The best overloaded method match for 'System.Windows.Media.Color.FromRgb(byte, byte, byte)' has some invalid arguments

Auch 3 Fehler wie: Cannot convert int to byte.

Aber wie funktioniert MSDN Beispiel?

+1

möglich Duplikat von [Wie bekomme ich Farbe aus Hex-Farbcode mit .NET?] (http://stackoverflow.com/questions/2109756/how-to-get-color-from-hex-color-code-using-net) – Sascha

+5

So dumm, dass sie das Standardformat #FFFFFF nicht zulassen. – MrFox

Antwort

236

Versuchen Sie stattdessen zu arbeiten:

(SolidColorBrush)(new BrushConverter().ConvertFrom("#ffaacc")); 
+48

Es ist diese Einfachheit, die mich mit WPF arbeiten lässt. –

+52

Es ist diese Art von Komplexität, die mir die Zusammenarbeit mit WPF nicht gefällt. – lfalin

+39

SO braucht Sarkasmus-Tags. –

15

How to get Color from Hexadecimal color code using .NET?

Das denke ich ist, was Sie sind, hoffen, dass es Ihre Frage beantwortet.

Um Ihren Code verwenden Convert.ToByte statt Convert.ToInt ...

string colour = "#ffaacc"; 

Color.FromRgb(
Convert.ToByte(colour.Substring(1,2),16), 
Convert.ToByte(colour.Substring(3,2),16), 
Convert.ToByte(colour.Substring(5,2),16)); 
9
using System.Windows.Media; 

byte R = Convert.ToByte(color.Substring(1, 2), 16); 
byte G = Convert.ToByte(color.Substring(3, 2), 16); 
byte B = Convert.ToByte(color.Substring(5, 2), 16); 
SolidColorBrush scb = new SolidColorBrush(Color.FromRgb(R, G, B)); 
//applying the brush to the background of the existing Button btn: 
btn.Background = scb; 
9

ich verwendet haben:

new SolidColorBrush((Color)ColorConverter.ConvertFromString("#ffaacc")); 
Verwandte Themen