In this article we will learn how to use canvas control in Silverlight 4.
Canvas Control
Canvas control is a simplest layout control. canvas control are used to defines a area within which you can place other controls by specifying the x and y coordinate position. When controls are placed within a Canvas, the x and y coordinates must be specified for each control using the attributes Canvas.Left and Canvas.Top.
Properties - These are the following properties of the canvas control.
Figure 1.
Height - Gets the rendered height of this element.
Width - Gets the rendered width of this element.
Background - Gets or sets a Brush that is used to fill the area between the borders of a Panel.
VerticalAlignment - Gets or sets the vertical alignment characteristics applied to this element when it is composed within a parent element such as a panel or items control.
Fill - fill property are used to fill the color.
For example
Drag a canvas and four Rectangle control on the form. The form looks like this.
Figure 2.
Now select the Rectangle controls and set the properties of every Rectangle.
Canvas.Left=25
Canvas.Top=40
Fill=green
Width=100
Height=100
The form looks like this after set the property of each Rectangle control.
Figure 3.
XAML Code:
<UserControl x:Class="SilverlightApplication18.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<Grid x:Name="LayoutRoot" Background="White" HorizontalAlignment="Stretch"VerticalAlignment="Top">
<Canvas Width="500" Background="#FF22CB76" Margin="0,0,-100,-349">
<Rectangle Canvas.Left="25" Canvas.Top="40" Fill="green" Width="100" Height="100" />
<Rectangle Canvas.Left="50" Canvas.Top="65" Fill="yellow" Width="100" Height="100" />
<Rectangle Canvas.Left="75" Canvas.Top="90" Fill="red" Width="100" Height="100" />
<Rectangle Canvas.Left="100" Canvas.Top="105" Fill="Purple" Width="100" Height="100" />
</Canvas>
</Grid>
</UserControl>
Now Save and run the application.
Figure 4.