Search code examples
wpfcolorsfillrectanglesconverters

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


I know how to set fill from WPF control.

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

but i can't get the color.

i want code like this.

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

Solution

  • If i understand you correctly you want to get the name of the color in your Rectangle.Fill Property as string (the way you would type it in xaml)?

    I have found a solution for this here

    in your code it should look like this:

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

    For my Rectangle <Rectangle Name="a" Fill="Aqua"></Rectangle> the String will return "Aqua".