简体   繁体   中英

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.

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());

An alternative way to do it:

        SolidColorBrush s = btn.Foreground as SolidColorBrush;
        string name="";
        foreach (KnownColor kc in Enum.GetValues(typeof(KnownColor)))
        {
            System.Drawing.Color known = System.Drawing.Color.FromKnownColor(kc);
            if (System.Drawing.Color.FromArgb(s.Color.A, s.Color.R, s.Color.G, s.Color.B).ToArgb() == known.ToArgb())
            {
                name = known.Name;
            }
        }
        MessageBox.Show(name);

the s.Color object is a System.Windows.Media.Color , so I am 'converting' it to System.Drawing.Color in order to find it's name using the KnownColor enum.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM