【问题标题】:Get buttons foreground color获取按钮前景色
【发布时间】:2014-06-02 07:06:58
【问题描述】:

尝试了很多组合,例如:

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

它返回: Windows.Ui.Xaml.Media.SolidColorBrush

但我需要知道颜色,例如:白色。

【问题讨论】:

    标签: c# windows xaml windows-8.1 brush


    【解决方案1】:

    您可以创建扩展方法并从Colors 类中获取颜色名称:

    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;
        }
    }
    

    ColorEx 类中,您可以使用 LINQ 使代码更具可读性和更短:

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

    例子:

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

    【讨论】:

      【解决方案2】:

      另一种方法:

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

      s.Color 对象是System.Windows.Media.Color,所以我将它“转换”为System.Drawing.Color,以便使用KnownColor 枚举找到它的名称。

      【讨论】:

        猜你喜欢
        • 2014-10-16
        • 1970-01-01
        • 2022-01-02
        • 1970-01-01
        • 2018-01-06
        • 2016-12-11
        • 2016-08-12
        • 2011-12-26
        • 1970-01-01
        相关资源
        最近更新 更多