从十六进制颜色值创建SolidColorBrush

Mah*_*aha 111 wpf

我想从Hex值创建SolidColorBrush,例如#ffaacc.我怎样才能做到这一点?

在MSDN上,我得到了:

SolidColorBrush mySolidColorBrush = new SolidColorBrush();
mySolidColorBrush.Color = Color.FromArgb(255, 0, 0, 255);
Run Code Online (Sandbox Code Playgroud)

所以我写了(考虑我的方法收到颜色#ffaacc):

Color.FromRgb(
  Convert.ToInt32(color.Substring(1, 2), 16), 
  Convert.ToInt32(color.Substring(3, 2), 16), 
  Convert.ToInt32(color.Substring(5, 2), 16));
Run Code Online (Sandbox Code Playgroud)

但这给出了错误

The best overloaded method match for 'System.Windows.Media.Color.FromRgb(byte, byte, byte)' has some invalid arguments

还有3个错误: Cannot convert int to byte.

但那么MSDN示例如何工作?

Chr*_*Ray 297

试试这个:

(SolidColorBrush)(new BrushConverter().ConvertFrom("#ffaacc"));
Run Code Online (Sandbox Code Playgroud)

  • 正是这种复杂性让我不喜欢使用WPF. (76认同)
  • 这种简单性让我喜欢使用WPF. (63认同)
  • SO需要讽刺标签. (50认同)
  • WPF的简单性未找到,为什么如此复杂地创建一种颜色. (5认同)

GJH*_*Hix 16

如何使用.NET从十六进制颜色代码中获取颜色?

我认为这就是你所追求的,希望它能回答你的问题.

要使代码工作,请使用Convert.ToByte而不是Convert.ToInt ...

string colour = "#ffaacc";

Color.FromRgb(
Convert.ToByte(colour.Substring(1,2),16),
Convert.ToByte(colour.Substring(3,2),16),
Convert.ToByte(colour.Substring(5,2),16));
Run Code Online (Sandbox Code Playgroud)


小智 13

我一直在用:

new SolidColorBrush((Color)ColorConverter.ConvertFromString("#ffaacc"));
Run Code Online (Sandbox Code Playgroud)


Mah*_*aha 9

using System.Windows.Media;

byte R = Convert.ToByte(color.Substring(1, 2), 16);
byte G = Convert.ToByte(color.Substring(3, 2), 16);
byte B = Convert.ToByte(color.Substring(5, 2), 16);
SolidColorBrush scb = new SolidColorBrush(Color.FromRgb(R, G, B));
//applying the brush to the background of the existing Button btn:
btn.Background = scb;
Run Code Online (Sandbox Code Playgroud)


Nei*_*l B 5

如果您不想每次都处理转换的痛苦,只需创建一个扩展方法。

public static class Extensions
{
    public static SolidColorBrush ToBrush(this string HexColorString)
    {
        return (SolidColorBrush)(new BrushConverter().ConvertFrom(HexColorString));
    }    
}
Run Code Online (Sandbox Code Playgroud)

然后像这样使用: BackColor = "#FFADD8E6".ToBrush()

或者,如果您可以提供一种方法来做同样的事情。

public SolidColorBrush BrushFromHex(string hexColorString)
{
    return (SolidColorBrush)(new BrushConverter().ConvertFrom(hexColorString));
}

BackColor = BrushFromHex("#FFADD8E6");
Run Code Online (Sandbox Code Playgroud)