Updated date:

Using Canvas in Wpf

Every platform has a canvas, and that its’ own kind of canvas. Every canvas feature is tricky, but at the same time quite useful.

For this tutorial you will need to use visual studio and establish WPF project, this works on both .NET framework and .NET CORE.

In the xaml, you only need to establish a canvas element. For the purpose of showcasing, this project will have three buttons for three different shapes that you can draw on canvas:

        <Canvas x:Name="cnv" HorizontalAlignment="Left" Height="200" Margin="225,115,0,0" VerticalAlignment="Top" Width="300"/>
        <Button Click="Line_bt_Click" x:Name="line_bt" Content="line" HorizontalAlignment="Left" Margin="118,358,0,0" VerticalAlignment="Top" Width="74"/>
        <Button Click="Circle_bt_Click" x:Name="circle_bt" Content="circle" HorizontalAlignment="Left" Margin="225,358,0,0" VerticalAlignment="Top" Width="74"/>
        <Button Click="Square_bt_Click" x:Name="square_bt" Content="square" HorizontalAlignment="Left" Margin="352,358,0,0" VerticalAlignment="Top" Width="74"/>

We will be drawing line, circle (ellipse) and square (rectangular).

Now that we have the canvas, we can go to the c# and we will start with the line

private void Line_bt_Click(object sender, RoutedEventArgs e)
            Line ln = new Line();
            ln.Stroke = SystemColors.GrayTextBrush;
            ln.X1 = 0;
            ln.Y1 = 0;
            ln.X2 = 300;
            ln.Y2 = 200;

as you can see, you first need to construct the Line object, afterwards you need to set some properties to the object. The Stroke property sets the color of the line, the next for properties will declare the start and end points for the line. X1 and Y1 coordinate set, will be the point where the line begins then X2 and Y2 will be the end point. Once you have those properties set, you need to add the object to the canvas object Children list, You can add as many as you want.

The second shape is an ellipse or in this case — a circle

private void Circle_bt_Click(object sender, RoutedEventArgs e)
           Ellipse el = new Ellipse();
            el.Stroke = SystemColors.HighlightBrush;
            el.Width = 100;
            el.Height = 100;

everything is very similar to the line, one thing to note here is that you need to set height and width the same to get a circle

The last shape is the rectangular

 private void Square_bt_Click(object sender, RoutedEventArgs e)
            Rectangle sq = new Rectangle();
            sq.Stroke = SystemColors.HighlightBrush;
            sq.Width = 100;
            sq.Height = 100;
            sq.Margin = new Thickness(100, 0, 0, 0);

In the last shape we add one additional parameter, which is the margin. Normally, when you draw a shape it will start at (0;0) coordinate, so if you want to put it somewhere else in the canvas you need to set a margin. As you can see, you have to use Thickness to set margin in WPF.

Related Articles