我想让用户可以设置颜色,就像在Blend或Photoshop中使用HEX值一样。如何存储并在我的XAML UI中使用?
答案 0 :(得分:0)
这可能是使用标准Windows.UI.Color
类选择颜色的最简单方法。但要将其转换为HEX值,它很简单:
Windows.UI.Color c = Windows.UI.Colors.Red;
string hexString = string.Format("#{0:X2}{1:X2}{2:X2}", c.R, c.G, c.B);
要在XAML中使用HEX值,您必须使用转换器。例如:
public class HexColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
if (!(value is Windows.UI.Color)) return null;
Windows.UI.Color c = (Windows.UI.Color)value;
string hex = string.Format("#{0:X2}{1:X2}{2:X2}", c.R, c.G, c.B);
return hex;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
if (!(value is string)) return null;
Windows.UI.Color c = new Windows.UI.Color();
string t = (string)value;
try
{
c.A = (byte)255;
c.R = (byte)int.Parse(t.Substring(1, 2), System.Globalization.NumberStyles.HexNumber);
c.G = (byte)int.Parse(t.Substring(3, 2), System.Globalization.NumberStyles.HexNumber);
c.B = (byte)int.Parse(t.Substring(5, 2), System.Globalization.NumberStyles.HexNumber);
}
catch
{
throw (new ArgumentException("Invalid color. Must be something like #AABBCC"));
}
return c;
}
}
有关使用转换器的更多信息,see MSDN