views:

94

answers:

4

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?

+2  A: 
Rectangle blueRectangle = new Rectangle();
// Fill rectangle with blue color
blueRectangle.Fill = blueBrush;
VoodooChild
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. Can you advise?
xarzu
Stroke is for the border of the rectangle and fill is for the interior of the rectangle. If you have a textblock inside the rectangle, how do you fill the rectangle color background without erasing the textblock?
xarzu
+2  A: 

Set the x:Name property in your XAML to what you want to refer to the rectangle as in your c# code. Then, you can access all of the properties of the rectangle in code, such as whateverYouNamedIt.Fill

Donnie
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. Can you advise?
xarzu
+1  A: 

Assuming you named your rectangle myRectangle, you can color it using the Fill property:

myRectangle.Height = 200;
myRectangle.Width = 200;
myRectangle.Stroke = new SolidColorBrush(Color.FromRgb(0, 111, 0));
myRectangle.Fill = new SolidColorBrush(Color.FromRgb(0, 111, 111));
Brian R. Bondy
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. Can you advise?
xarzu
Stroke is for the border of the rectangle and fill is for the interior of the rectangle. If you have a textblock inside the rectangle, how do you fill the rectangle color background without erasing the textblock?
xarzu
A: 

The way that worked for me is to have an embedded textblock and change the background to the textblock.

xarzu