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.
This should draw your rectangle as a 200×200 black square, provided
front_canvasis displayed correctly.The main reasons this would not draw are:
front_canvasis not visiblefront_canvasis not in the visual tree and being displayed correctlyFrameworkElementis obscuringfront_canvas, at least the upper left corner.Note that you’d typically also want to set
StrokeThicknessif you want to see theStrokeyou specify.