8
有誰知道如何將表示顏色的字符串轉換爲WPF中的SolidColorBrush
?WPF SolidColorBrush困境
對於e.g:
string colorRed = "Red";
SolidColorBrush fromStringToColor = new SolidColorBrush(colorRed);
這就是那種我想要完成的任務。 有什麼建議嗎?
在此先感謝。
有誰知道如何將表示顏色的字符串轉換爲WPF中的SolidColorBrush
?WPF SolidColorBrush困境
對於e.g:
string colorRed = "Red";
SolidColorBrush fromStringToColor = new SolidColorBrush(colorRed);
這就是那種我想要完成的任務。 有什麼建議嗎?
在此先感謝。
您必須將字符串轉換爲System.Windows.Media.Color,您可以使用靜態ColorConverter.ConvertFromString方法做:
string colorRed = "Red";
Color c = (Color)ColorConverter.ConvertFromString(colorRed);
SolidColorBrush fromStringToColor = new SolidColorBrush(c);
private SolidColorBrush GetColorFromString(string color)
{
if (color.StartsWith("#"))
{
if (color.Length == 9)
return new SolidColorBrush(
Color.FromArgb(
Convert.ToByte(color.Substring(1, 2), 16),
Convert.ToByte(color.Substring(3, 2), 16),
Convert.ToByte(color.Substring(5, 2), 16),
Convert.ToByte(color.Substring(7, 2), 16)
)
);
else
if (color.Length == 7)
return new SolidColorBrush(
Color.FromArgb(
0xff,
Convert.ToByte(color.Substring(1, 2), 16),
Convert.ToByte(color.Substring(3, 2), 16),
Convert.ToByte(color.Substring(5, 2), 16)
)
);
}
else
{
Type colorType = (typeof(System.Windows.Media.Colors));
if (colorType.GetProperty(color) != null)
{
object o = colorType.InvokeMember(color,
System.Reflection.BindingFlags.GetProperty, null, null, null); if (o != null)
{
return new SolidColorBrush((Color)o);
}
}
}
return new SolidColorBrush(Colors.Transparent);
}
SolidColorBrush c1 = GetColorFromString("Red");
SolidColorBrush c2 = GetColorFromString("#ffff0000");
SolidColorBrush c3 = GetColorFromString("#ff0000");
這不是真正從像「一串紅「但是,是嗎? – crdx 2012-10-30 09:09:31