Search code examples
c#wpffillrectangles

How can I get the filled color value in a WPF rectangle?


For example,Consider:

Rectangle rect = new Rectangle();
rect.Fill = Brushes.Cyan;

Can I get the color value from a rect like this? I tried to extract color values, but it did not work.


Solution

  • Yes, you can, but you need to cast Fill to correct Brush class, since Brush does not have color property (you need to cast it to SolidColorBrush):

    Rectangle rect = new Rectangle();
    rect.Fill = Brushes.Cyan;
    System.Diagnostics.Debug.WriteLine(((SolidColorBrush)rect.Fill).Color);
    

    There are different brushes in WPF, for some of them Color does not make sense.