Reputation: 241
I have convert "Windows.UI.Xaml.Media.Brush" to "Windows.UI.Color". But VS return error. Tell me please how can I do this conversion correctly?
Upvotes: 4
Views: 5784
Reputation: 89
There is a workaround if you're converting it to a string, then the string to bytes and then the bytes to color:
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));
in the last line you take the hexadecimal string values and convert them to a byte.
Make sure that you're brush is made out of one single color and not null, otherwise you'll get an exception.
Upvotes: 0
Reputation: 559
You can convert Brush to color, but you have to write it explicitly. To do so just do this:
StackPanel pane = new StackPanel()
{
Background = Background = new SolidColorBrush(new Windows.UI.Color() { A = 255, R = 25, B = 0, G = 0})
}
This works for EVERY single UIElement as long as you assign the Background property properly.
Upvotes: 1
Reputation: 13850
You cannot convert a brush to a color. The concept of a brush cannot be reduced to a color, as it could be a gradient of colors, or an image etc.
The conversion only makes sense for the special case of SolidColorBrush. I am guessing that's what you are after. Here is how you do it in code:
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");
Thanks, Stefan Wick - Windows Developer Platform
Upvotes: 9