wpf: How do I get the color from a hexadecimal color code using .NET?

wpf: How do I get the color from a hexadecimal color code using .NET?

Asked on October 30, 2018 in WPF.
Add Comment


  • 5 Answer(s)

    System.Drawing.Color or System.Windows.Media.Color  is used in WPF.

    for ex:

    using System.Windows.Media;
    Color color = (Color)ColorConverter.ConvertFromString("#FFDFD991");
    
    Answered on October 30, 2018.
    Add Comment

      Assuming that HTML type RGB codes , use the ColorTranslator class: 

    System.Drawing.Color col = System.Drawing.ColorTranslator.FromHtml("#FFCC66");
    

      If, however you are using an ARGB hex code, you can use the ColorConverter class from the System.Windows.Media namespace:

    Color col = ColorConverter.ConvertFromString("#FFDFD991") as Color;
    //or = (Color) ColorConverter.ConvertFromString("#FFCC66") ;
    
    Answered on October 30, 2018.
    Add Comment

      Want to avoid  ColorTranslator, it can be done easily:

    string colorcode = "#FFFFFF00";
    int argb = Int32.Parse(colorcode.Replace("#", ""), NumberStyles.HexNumber);
    Color clr = Color.FromArgb(argb);
    The colorcode is just the hexadecimal representation of the ARGB value.
    

    EDIT

      If we need to use 4 values instead of a single integer, we can use this (combining several comments):

    string colorcode = "#FFFFFF00";
    colorcode = colorcode.TrimStart('#');
    Color col; // from System.Drawing or System.Windows.Media
    if (colorcode.Length == 6)
      col = Color.FromArgb(255, // hardcoded opaque
        int.Parse(colorcode.Substring(0,2), NumberStyles.HexNumber),
        int.Parse(colorcode.Substring(2,2), NumberStyles.HexNumber),
        int.Parse(colorcode.Substring(4,2), NumberStyles.HexNumber));
    else // assuming length of 8
      col = Color.FromArgb(
        int.Parse(colorcode.Substring(0, 2), NumberStyles.HexNumber),
        int.Parse(colorcode.Substring(2, 2), NumberStyles.HexNumber),
        int.Parse(colorcode.Substring(4, 2), NumberStyles.HexNumber),
    int.Parse(colorcode.Substring(6, 2), NumberStyles.HexNumber));
    
    Answered on October 30, 2018.
    Add Comment

    using System.Windows.Media;

    Color color = (Color)ColorConverter.ConvertFromString(“#FFDFD991”);

    Answered on February 24, 2019.
    Add Comment

    using System.Windows.Media;

    Color color = (Color)ColorConverter.ConvertFromString(“#FFDFD991”);

    Answered on February 24, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.