How to convert color code into media.brush? [duplicate]
I have a rectangle that i want to fill with a color. When i write Fill = "#FFFFFF90"
it shows me an error:
Cannot implicitly convert type 'string' to 'System.Windows.Media.Brush
Please give me some advice.
You could use the same mechanism the XAML reading system uses: Type converters
var converter = new System.Windows.Media.BrushConverter();
var brush = (Brush)converter.ConvertFromString("#FFFFFF90");
Fill = brush;
In code, you need to explicitly create a Brush
instance:
Fill = new SolidColorBrush(Color.FromArgb(0xff, 0xff, 0x90))
For WinRT (Windows Store App)
using Windows.UI;
using Windows.UI.Xaml.Media;
public static Brush ColorToBrush(string color) // color = "#E7E44D"
{
color = color.Replace("#", "");
if (color.Length == 6)
{
return new SolidColorBrush(ColorHelper.FromArgb(255,
byte.Parse(color.Substring(0, 2), System.Globalization.NumberStyles.HexNumber),
byte.Parse(color.Substring(2, 2), System.Globalization.NumberStyles.HexNumber),
byte.Parse(color.Substring(4, 2), System.Globalization.NumberStyles.HexNumber)));
}
else
{
return null;
}
}