This article is compatible with the latest version of Silverlight.
Introduction
The Canvas is the simplest layout control used as a container for other Silverlight controls. The inner controls are positioned absolutely towards its left and top sides.
See also:
Silverlight Layout controls
Grid Article
StackPanel Article
Overview
The following example demonstrates the use of the Canvas:
We want to have a rectangle positioned 100 pixels from the left side and 50 pixels from the top side:
The child controls of the Canvas are positioned absolutely towards its left and top sides by their “Canvas.Left” and “Canvas.Top” attached properties.
Here is the XAML code:
<UserControl x:Class="Canvas2.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300">
<Canvas x:Name="cnvControlHolder" Background="White" Height="300" Width="400">
<Rectangle x:Name="rectTest" Canvas.Left="100" Canvas.Top="50" Fill="Blue" Width="60" Height="40"></Rectangle>
</Canvas>
</UserControl>
Other important property which you can set to the controls inside the canvas is the Canvas.ZIndex. just like the z-index in CSS. Here is a little example:
We want to have a button in front of a rectangle:
<Canvas x:Name="cnvControlHolder" Background="White" Height="300" Width="400">
<Rectangle x:Name="rectTest" Canvas.Left="100" Canvas.Top="50" Canvas.ZIndex="0" Fill="Blue" Width="60" Height="40"></Rectangle>
<Button x:Name="btnTest" Canvas.Left="120" Canvas.Top="70" Canvas.ZIndex="1" Content="Button :)"></Button>
</Canvas>
We have a button with Canvas.ZIndex="1" that is above our Rectangle because its z index is bigger. There is nothing you can misunderstand.
You can get or set the “Canvas.Left”, “Canvas.Top” and “Canvas.ZIndex” attached properties programatically using the static methods of the Canvas class.
The following example demonstrates it:
Code behind:
public partial class Page : UserControl
{
public Page()
{
InitializeComponent();
Canvas.SetTop( this.rectTest, 80 );
Canvas.SetLeft( this.rectTest, 130 );
Canvas.SetZIndex( this.rectTest, 2 );
}
}
Result:
Here is another example where we get the three properties and increase them:
Canvas.SetTop( this.rectTest, Canvas.GetTop( this.rectTest ) + 30 );
Canvas.SetLeft( this.rectTest, Canvas.GetLeft( this.rectTest ) + 30 );
Canvas.SetZIndex( this.rectTest, Canvas.GetZIndex( this.rectTest ) + 2 );
The result is the same.
Conclusion
This article is a brief description of the key features of the Canvas control. It targets the developer who has just started with the Silverlight controls. Any comments are welcome.
Reference
http://silverlight.net/learn/tutorials.aspx
http://msdn2.microsoft.com/en-us/library/system.windows.controls.canvas(VS.95).aspx