Search code examples
c#windowsxamlwindows-8.1brush

Get buttons foreground color


Tried many combinations such as:

        SolidColorBrush b = (SolidColorBrush)myButton.Foreground;
        b.Color.ToString();

It returns: Windows.Ui.Xaml.Media.SolidColorBrush

But I need to know the color, ex: White.


Solution

  • You can create extension method and get color name from Colors class:

    public static class ColorEx
    {
        public static string GetColorName(this SolidColorBrush scb)
        {
            string result = null;
            foreach (var pi in typeof(Colors).GetRuntimeProperties())
            {
                Color c = (Color)pi.GetValue(null);
                if (c == scb.Color)
                {
                    result = pi.Name;
                    break;
                }
            }
            return result;
        }
    }
    

    In the ColorEx class you can use LINQ to make code more readable and much shorter:

    public static class ColorEx
    {
        public static string GetColorName(this SolidColorBrush scb)
        {
            return typeof(Colors).GetRuntimeProperties().Where(x => (Color)x.GetValue(null) == scb.Color).Select(x => x.Name).FirstOrDefault();
        }
    }
    

    Example:

    SolidColorBrush b = (SolidColorBrush)myButton.Foreground;
    Debug.WriteLine(b.GetColorName());