This documentation is archived and is not being maintained.

How to: Absolutely Position Elements in a Canvas

This example shows how to use the Canvas control to absolutely position content.

The following example produces three Rectangle elements, each element 100 pixels.

The first Rectangle is red, and its upper-left (x, y) position is specified as (0, 0). The second Rectangle is green, and its upper-left position is (100, 100), which is just below, and to the right of, the first square. The third Rectangle is blue, and its upper-left position is (50, 50). Hence, the third Rectangle covers the lower-right quadrant of the first Rectangle and the upper-left quadrant of the second.

Because the third Rectangle is laid out last, it appears to be on top of the other two squares—that is, the overlapping portions assume the color of the third Rectangle.

// Create the application's main window
mainWindow = new Window ();
mainWindow.Title = "Canvas Sample";

// Create the Canvas
myParentCanvas = new Canvas();
myParentCanvas.Width = 400;
myParentCanvas.Height = 400;

// Define child Canvas elements
myCanvas1 = new Canvas();
myCanvas1.Background = Brushes.Red;
myCanvas1.Height = 100;
myCanvas1.Width = 100;
Canvas.SetTop(myCanvas1, 0);
Canvas.SetLeft(myCanvas1, 0);

myCanvas2 = new Canvas();
myCanvas2.Background = Brushes.Green;
myCanvas2.Height = 100;
myCanvas2.Width = 100;
Canvas.SetTop(myCanvas2, 100);
Canvas.SetLeft(myCanvas2, 100);

myCanvas3 = new Canvas();
myCanvas3.Background = Brushes.Blue;
myCanvas3.Height = 100;
myCanvas3.Width = 100;
Canvas.SetTop(myCanvas3, 50);
Canvas.SetLeft(myCanvas3, 50);

// Add child elements to the Canvas' Children collection

// Add the parent Canvas as the Content of the Window Object
mainWindow.Content = myParentCanvas;
mainWindow.Show ();
<Page WindowTitle="Canvas Sample" xmlns="">
  <Canvas Height="400" Width="400">
    <Canvas Height="100" Width="100" Top="0" Left="0" Background="Red"/>
    <Canvas Height="100" Width="100" Top="100" Left="100" Background="Green"/>
    <Canvas Height="100" Width="100" Top="50" Left="50" Background="Blue"/>