 |
Only <Canvas> elements that have a fixed width
and height show their background color. If you omit this information,
the background remains the default, which in our example is
white.
|
|
Of course, these canvases overlap each other. Silverlight uses the
following approach: all elements are stacked onto each other, so there is
a (virtual) third dimension. Therefore, the text from Example 1 resides on top of all canvases, since this element
comes last in the document. This is why the text can be seen at all. In
CSS, there is a property called z-index that assigns the
"z coordinate" of an element: the higher the value,
the further up on the stack it is.
Silverlight uses the same principle. You may assign a z-index by
setting the Canvas.ZIndex
property. Note that you can also nest z-index values; however, these
values are compared only on the same element level. Assume that you have a
canvas with z-index 3 that contains two
rectangles with z-index 2 and z-index 1. The rectangle with the higher z-index
is placed above the one with the lower z-index. However, the outer canvas
will not overlap the rectangles, although its z-index is higher.
Example 2 is a variation of Example 1: everything except the outer canvas is gone, but we
added rectangles. Usually they would overlap, similar to Figure 1, but this time we set Canvas.ZIndex so that the "inner" elements have
a lower z-index. Therefore, the first rectangle is drawn over the second
one, the second one is drawn over the third one, and so on. The lowest
z-index is assigned to the text block. This text block is now overlapped
by the blue rectangle. Therefore, the text itself is not visible, as Figure 2 shows.
Example 2. Setting the z-index, the XAML file (Page.xaml, project
ZIndex)
<UserControl x:Class="ZIndex.Page"
xmlns="http://schemas.microsoft.com/client/2007"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300">
<Grid x:Name="LayoutRoot" Background="White">
<Canvas Width="500" Height="500" Background="White">
<Rectangle Canvas.Left="50" Canvas.Top="50" Fill="Red"
Width="200" Height="200" Canvas.ZIndex="5"/>
<Rectangle Canvas.Left="100" Canvas.Top="100" Fill="Green"
Width="200" Height="200" Canvas.ZIndex="4"/>
<Rectangle Canvas.Left="150" Canvas.Top="150" Fill="Yellow"
Width="200" Height="200" Canvas.ZIndex="3"/>
<Rectangle Canvas.Left="200" Canvas.Top="200" Fill="Blue"
Width="200" Height="200" Canvas.ZIndex="2"/>
<TextBlock Canvas.Left="250" Canvas.Top="250" FontSize="20"
Text="Silverlight" Canvas.ZIndex="1"/>
</Canvas>
</Grid>
</UserControl>