How to Absolute Position Elements in a Canvas

The following code snippet creates a Canvas elements and places three Rectangle elements on it and sets Rectangles' positions using Canvas.Top and Canvas.Left properties in XAML.

<Page x:Class="CanvasAbsolutePosition.Page1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Page1" Name="MainPage">
   
    <!-- Create a Canvas -->
    <Canvas Height="400" Width="400">
        <!-- Create three Rectangle elements and position them using Canvas.Top and Canvas.Left -->
        <Rectangle Height="100" Width="100" Canvas.Top="0" Canvas.Left="0" Fill="Red"/>
        <Rectangle Height="100" Width="100" Canvas.Top="100" Canvas.Left="100" Fill="Green"/>
        <Rectangle Height="100" Width="100" Canvas.Top="50" Canvas.Left="50" Fill="Blue"/>
    </Canvas>

</Page>

The output looks like this:

The following code snippet shows how to do the same in WPF code behind using C# language.

private void CreateCanvasDynamically()

{

    // Create the Canvas

    Canvas rootcanvas = new Canvas();

    rootcanvas.Width = 400;

    rootcanvas.Height = 400;

 

    // Define child Canvas elements

    Rectangle redRectangle = new Rectangle ();

    redRectangle.Fill = Brushes.Red;

    redRectangle.Height = 100;

    redRectangle.Width = 100;

    Canvas.SetTop(redRectangle, 0);

    Canvas.SetLeft(redRectangle, 0);

    rootcanvas.Children.Add(redRectangle);

 

    Rectangle greenRectangle = new Rectangle();

    greenRectangle.Fill = Brushes.Green;

    greenRectangle.Height = 100;

    greenRectangle.Width = 100;

    Canvas.SetTop(greenRectangle, 100);

    Canvas.SetLeft(greenRectangle, 100);

    rootcanvas.Children.Add(greenRectangle);

 

    Rectangle blueRectangle = new Rectangle();

    blueRectangle.Fill = Brushes.Blue;

    blueRectangle.Height = 100;

    blueRectangle.Width = 100;

    Canvas.SetTop(blueRectangle, 50);

    Canvas.SetLeft(blueRectangle, 50);

    rootcanvas.Children.Add(blueRectangle);

 

    // Add Canvas to the Page as Content

    MainPage.Content = rootcanvas;

}

Copy this code and paste in your code behind file and call this method from Page1 constructor after InitializeComponent method like this:

public Page1()

{

    InitializeComponent();

 

    CreateCanvasDynamically();

}