I'm trying to draw a Rectangle
on a Canvas
as follows:
System.Windows.Shapes.Rectangle rect;
rect = new System.Windows.Shapes.Rectangle();
rect.Stroke = new SolidColorBrush(Colors.Black);
rect.Fill = new SolidColorBrush(Colors.Black);
rect.Width=200;
rect.Height=200;
Canvas.SetLeft(rect,0);
Canvas.SetTop(rect,0);
front_canvas.Children.Add(rect);
Why would this code not draw a rectangle?
The canvas is defined in the associated XAML as follows:
<Canvas Height="200" Width="200" Name="front_canvas" Grid.Row="1" Grid.Column="0">
</Canvas>
The canvas shows up fine. I can tell because of the gap it leaves in the layout grid.
Creating a RectangleThe Rectangle element in XAML creates a rectangle shape. The following code snippet creates a rectangle by setting its width and height properties to 200 and 100 respectively. The code also sets the black stroke of width 4.
To draw a line, create a Line element. Use its X1 and Y1 properties to set its start point; and use its X2 and Y2 properties to set its end point. Finally, set its Stroke and StrokeThickness because a line without a stroke is invisible. Setting the Fill element for a line has no effect, because a line has no interior.
Use its Stroke property to specify the Brush that is used to paint the outline of the ellipse. The StrokeThickness property specifies the thickness of the ellipse outline. To draw a circle, make the Width and Height of the Ellipse element equal to each other.
This should draw your rectangle as a 200x200 black square, provided front_canvas
is displayed correctly.
Why would this code not draw a rectangle?
The main reasons this would not draw are:
front_canvas
is not visiblefront_canvas
is not in the visual tree and being displayed correctlyFrameworkElement
is obscuring front_canvas
, at least the upper left corner.Note that you'd typically also want to set StrokeThickness
if you want to see the Stroke
you specify.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With