Canvas Panel in WPF


In WPF, a Canvas Panel has a very simple layout. We can position any object using its two properties:

  • Canvas.Left

  • Canvas.Top

Note: A Canvas panel does not resize automatically when our normal application resizes in the browser.

Here is an example of a Canvas panel:

<Canvas Background="Pink" Width="250" Height="100">
</Canvas>

Clipboard01.jpg

Now for an example in which we specify a Button control in the Canvas and set the position of the button in the Canvas with the help of Canvas.Top and Canvas.Left.

Step 1 : First we write the code for the canvas:

<Canvas Background="Pink" Width="250" Height="100">
</Canvas> 


Step 2 :
 After that we take a Button Control in it and set its position in the Canvas:

<Canvas Background="Pink" Width="250" Height="100">
<Button Canvas.Left="10" Canvas.Top="20">First</Button>
 </Canvas>

Clipboard02.jpg

Now we take another example of Position. Here we take four Button Controls which are in the four corners of the canvas:

<Window x:Class="CanvasPanelInWPF.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
     Title="Window1" Height="300" Width="300">
     <Grid>
         <Canvas Background="Pink" Width="250" Height="100">
            <Button Canvas.Left="5" Canvas.Top="10">First</Button>
            <Button Canvas.Left="200" Canvas.Top="10">Second</Button>
            <Button Canvas.Left="5" Canvas.Top="70">Three</Button>
            <Button Canvas.Left="210" Canvas.Top="70">Four</Button>
         </Canvas>
     </Grid>
</Window>

Clipboard03.jpg

It is so easy to use the concept of positions in a Canvas panel. If we want to set the Height and Width of our application in the Browser or if we want to see our application in the entire window of our Browser, it can be done easily; we can do it by removing the Height and Width property of the Element.

<Window x:Class="CanvasPanelInWPF.Window1"
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
     Title="Window1" Height="300" Width="300">
     <Grid>
        <Canvas Background="Pink">
        </Canvas>
     </Grid>
</Window>

Clipboard04.jpg

Note : By Default, the root UserControl object is set to a width of 400 and a height of 300.

Up Next
    Ebook Download
    View all
    Learn
    View all