我如何从填充 属性 的矩形中获取颜色?

How do i get the color from Rectangle in fill property?

我知道如何从 WPF 控件设置填充。

Rectangle a = new Rectangle()
a.Fill = Brushes.Red;

但是我看不到颜色

我想要这样的代码。

string color = a.Fill; // Red
var color2 = a.Fill(T); // Brushes.Red
var color3 = a.Fill; // other object

如果我对你的理解是正确的,你想在 Rectangle.Fill 属性 中获取颜色名称作为字符串(你在 xaml 中输入的方式)?

我已经找到解决方法 here

在您的代码中,它应该如下所示:

      SolidColorBrush brush = (SolidColorBrush)a.Fill;
  Color c = brush.Color;
  var colorname = (from p in typeof(System.Drawing.Color).GetProperties()
                   where p.PropertyType.Equals(typeof(System.Drawing.Color))
                   let value = (System.Drawing.Color)p.GetValue(null, null)
                   where value.R == c.R &&
                         value.G == c.G &&
                         value.B == c.B &&
                         value.A == c.A
                   select p.Name).DefaultIfEmpty("unknown").First(); 

对于我的矩形 <Rectangle Name="a" Fill="Aqua"></Rectangle>,字符串将 return "Aqua"。