1. Canvas布局:通过其内部的控件的属性Canvas.Top、Canvas.Left、Canvas.ZIndex来定义以像素为单位的绝对布局。
2. StackPanel布局:是标准的流式布局:通过Orientation属性的值来确定是垂直显示(Vertical)还是水平显示(Horizontal)。
3. Grid布局:是一种类似Table的布局方式。通过<Grid.RowDefinitions>来定义行,<Grid.ColumnDefinitions>来定义列,通过ShowGridLines来定义是否显示边框。在其子元素中通过Grid.Row、Grid.RowSpan、Grid.Column、Grid.ColumnSpan来设置位置。
有时我们可以综合利用上述三种方式控制页面的布局。代码如下:
<UserControl x:Class="LayOut.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Canvas Background="AliceBlue">
<TextBlock Text="这是Canvas布局" Foreground="Red"></TextBlock>
<Ellipse Canvas.Left="10" Canvas.Top="20" Canvas.ZIndex="0" Width="100" Height="50" Fill="Blue"></Ellipse>
<Ellipse Canvas.Left="10" Canvas.Top="50" Canvas.ZIndex="1" Width="100" Height="50" Fill="Yellow"></Ellipse>
<TextBlock Text="这是StackPanel布局" Canvas.Left="120" Foreground="Green"></TextBlock>
<StackPanel Orientation="Horizontal" Canvas.Left="120" Canvas.Top="20">
<Ellipse Width="100" Height="50" Fill="Blue"></Ellipse>
<Ellipse Width="100" Height="50" Fill="Yellow"></Ellipse>
</StackPanel>
<StackPanel Orientation="Vertical" Canvas.Left="120" Canvas.Top="80">
<Ellipse Width="100" Height="50" Fill="Blue"></Ellipse>
<Ellipse Width="100" Height="50" Fill="Yellow"></Ellipse>
</StackPanel>
<TextBlock Text="这是Grid布局" Canvas.Left="320" Foreground="Blue"></TextBlock>
<Grid Canvas.Left="320" Canvas.Top="20" ShowGridLines="True" Background="Aqua">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Ellipse Grid.Row="0" Grid.Column="0" Width="100" Height="50" Fill="Blue"></Ellipse>
<Ellipse Grid.Row="1" Grid.Column="0" Width="100" Height="50" Fill="Yellow"></Ellipse>
<Ellipse Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="2" Width="100" Height="50" Fill="Red"></Ellipse>
<Ellipse Grid.Row="0" Grid.Column="1" Width="100" Height="50" Fill="Blue"></Ellipse>
<Ellipse Grid.Row="1" Grid.Column="1" Width="100" Height="50" Fill="Yellow"></Ellipse>
</Grid>
</Canvas>
</UserControl>
界面如下图:
至此,SilverlLight的布局方式介绍完毕,下一讲,我们将讲解SilverLight的基本控件。