Canvas is a solution for absolute positioning in XAML. Canvas
has four Attached Properties in its child elements: Canvas.Top, Canvas.Left, Canvas.Right
and Canvas.Bottom.
These attributes specify the distance between the top left
corner of an element and its parent Canvas. Obviously, by setting one of
Canvas.Top and Canvas.Bottom and one of Canvas.Left and Canvas.Right, you will
get the result and do not need to set others. However, if you set both
attributes, Canvas.Top and Canvas.Left are preferred. Also, you can set only
one of these attributes for an element.
Listing 11 and Figure 11 help you to see the concept of
Canvas in a simple example.
Listing 11
<Window x:Class="LayoutinXAML.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Layout in XAML" Height="300" Width="300"
>
<Canvas>
<TextBox Background="Coral" Grid.Row="0" Grid.Column="0"
Canvas.Top="10" Canvas.Left="20">
ASP Alliance 1
</TextBox>
<TextBox Background="Plum" Grid.Row="0" Grid.Column="1"
Canvas.Bottom="60" Canvas.Left="40">
ASP Alliance 2
</TextBox>
<TextBox Background="Aquamarine" Grid.Row="1" Grid.Column="0"
Canvas.Top="80" Canvas.Right="110">
ASP Alliance 3
</TextBox>
<TextBox Background="Teal" Grid.Row="1" Grid.Column="1"
Canvas.Bottom="95" Canvas.Right="30">
ASP Alliance 4
</TextBox>
</Canvas>
</Window>
Figure 11
I said Canvas Attached Properties have relative values to
their parent Canvas elements. So if you nest a Canvas element within another
and declare some elements in second Canvas, those elements will get their
position from their direct parent Canvas. Listing 12 and Figure 12 show this
concept.
Listing 12
<Window x:Class="LayoutinXAML.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Layout in XAML" Height="300" Width="300"
>
<Canvas>
<TextBox Background="Coral" Grid.Row="0" Grid.Column="0"
Canvas.Top="10" Canvas.Left="20">
ASP Alliance 1
</TextBox>
<TextBox Background="Plum" Grid.Row="0" Grid.Column="1"
Canvas.Top="60" Canvas.Left="40">
ASP Alliance 2
</TextBox>
<Canvas Canvas.Top="120" Canvas.Left="140">
<TextBox Background="Aquamarine" Grid.Row="1" Grid.Column="0"
Canvas.Top="5" Canvas.Left="10">
ASP Alliance 3
</TextBox>
<TextBox Background="Teal" Grid.Row="1" Grid.Column="1"
Canvas.Top="60" Canvas.Left="50">
ASP Alliance 4
</TextBox>
</Canvas>
</Canvas>
</Window>
Figure 12