我已经将“Windows.UI.Xaml.Media.Brush”转换为“Windows.UI.Color”。但是,VS返回错误。请告诉我如何正确进行此转换?
你无法将画刷转换为颜色。画刷的概念不能简化为颜色,因为它可以是一组颜色的渐变或者是一个图像等。
转换只对SolidColorBrush这种特殊情况有意义。我猜这就是你想要的。以下是代码实现:
Windows.UI.Color colorFromBrush;
if (brush is SolidColorBrush)
colorFromBrush = (brush as SolidColorBrush).Color;
else
throw new Exception("Can't get color from a brush that is not a SolidColorBrush");
感谢,Stefan Wick - Windows 开发平台
StackPanel pane = new StackPanel()
{
Background = Background = new SolidColorBrush(new Windows.UI.Color() { A = 255, R = 25, B = 0, G = 0})
}
如果你正在将它转换为字符串,然后将字符串转换为字节,最后将字节转换为颜色,那么有一个解决方法:
var brushString = Foreground.ToString(); // brushString equals "#FF000000" (in case of black brush)
var brushWithoutHash = brushString.Substring(1); // brushWithoutHash equals "FF000000"
var color = Color.FromArgb(Convert.ToByte(brushWithoutHash.Substring(0, 2), 16), Convert.ToByte(brushWithoutHash.Substring(2, 2), 16), Convert.ToByte(brushWithoutHash.Substring(4, 2), 16), Convert.ToByte(brushWithoutHash.Substring(6, 2), 16));
在最后一行,您将获取十六进制字符串值并将其转换为字节。
确保您的画笔只使用单一颜色而不是空值,否则会出现异常。