How do you color a rectangle in C# that has been declared in XAML in WPF?

Topics: Prism v2 - WPF 4
May 22, 2010 at 3:19 AM
Edited May 22, 2010 at 12:59 PM

How do you color a rectangle in C# that has been declared in XAML in WPF?

There is a rectangle control in XAML.  In my C# code there are times in which it would be nice to fill the background color.  How does one do this?

The rectangle has a text block nested inside. The Fill works to color the whole rectangle but it also blocks out the text. On the other hand, using the stroke first colors the rectangle and I can modify the enclosed test but the rectangle does not have a boarder.

The way to do it might be to bind the Rectangle background colouur to a property and use INotifyPropertyChanged to trigger the update of the colour based on the change.

How do I bind the Rectangle background colour to a property?

Developer
May 28, 2010 at 10:47 PM

Hi,

If I understood your scenario correctly, you want to change the text’s color depending on the rectangle’s background, so that it isn’t blocked out. A possible approach for that would be to bind the text’s foreground property to the rectangle’s background, but using a value converter to define an appropriate color for the text depending on the rectangle’s background (i.e. chose white for the text if the background is black). You can find an example of value converters in this blog post.

As this is not related to Prism, you may get better support at the WPF forums.

I hope you find this helpful.

Guido Leandro Maliandi
http://blogs.southworks.net/gmaliandi