在Silverlight中提供了3种类型的布局面板;
1.Canvas - 绝对定位子元素x,y的位置。
Canvas定义了一个区域,通过制定x和y坐标的值来放置其他的控件。这样在Canvas中可能重叠多个控件。与通常的HTML相反,当控件重叠时,被重叠的控件可以被其他控件隐藏。当控件放置在Canvas中,使用Canvas.Left和Canvas.Top属性为每个控件指定x和y坐标。
此示例演示在Canvas中放置矩形控件并指定x和y坐标:
< Rectangle Canvas.Left ="25" Canvas.Top ="40" Fill ="green" width ="100" Height ="100" />
</ Canvas >
上面的xaml标签定义了一个宽和高各为100像素的绿色矩形,它离Canvas左边25像素,顶端40像素。
下面例子演示3个矩形相互重叠:
< Rectangle Canvas.Left ="25" Canvas.Top ="40" Fill ="green" Width ="100" Height ="100" />
< Rectangle Canvas.Left ="50" Canvas.Top ="65" Fill ="yellow" Widt ="100" Height ="100" />
< Rectangle Canvas.Left ="75" Canvas.Top ="90" Fill ="red" Width ="100" Height ="100" />
</ Canvas >
2.StackPanel - 子元素按行或者列来进行页面布局。
StackPanel支持用行或列的方式来进行页面布局,默认情况下所有的子元素会垂直的排列显示,如下面的xaml声明三个矩形:
< Rectangle Fill ="#0099ff" Stroke ="White" Width ="100" Height ="50" Margin ="10" />
< Rectangle Fill ="#0099ff" Stroke ="White" Width ="100" Height ="50" Margin ="10" />
< Rectangle Fill ="#0099ff" Stroke ="White" Width ="100" Height ="50" Margin ="10" />
</ StackPanel >
我们也可以指定为水平排列,通过设置StackPanel的Prientation属性为Horizontal。
3.Grid - 子元素放在行列表格中进行布局。
Grid控件类似于HTML中的Table,只不过子元素不用放在单元格中。通过<Grid.RowDefinition>和<Grid.ColumnDefinitions>来定义Grid的行和列,使用Grid.Row和Grid.Column两个附加属性指定子元素在Grid中显示的位置,这是一种非常灵活的布局方式;
< Grid.RowDefinitions >
< RowDefinition Height ="40" />
< RowDefinition Height ="*" />
</ Grid.RowDefinitions >
< Grid.ColumnDefinitions >
< ColumnDefinition Width ="100" />
< ColumnDefinition Width ="*" />
</ Grid.ColumnDefinitions >
< TextBlock Grid.Row ="0" Grid.Column ="0" Text ="UserName:" VerticalAlignment ="Center" Foreground ="White" ></ TextBlock >
< TextBlock Grid.Row ="1" Grid.Column ="0" Text ="Password:" VerticalAlignment ="Center" Foreground ="Wheat" ></ TextBlock >
< TextBox Grid.Row ="0" Grid.Column ="1" Width ="200" Height ="30" HorizontalAlignment ="Left" ></ TextBox >
< TextBox Grid.Row ="1" Grid.Column ="1" Width ="200" Height ="30" HorizontalAlignment ="Left" ></ TextBox >
</ Grid >
定义了一个两行两列的Grid,做一个简单的用户登录布局,为了明显起见,把ShowGridLines属性设为True,以便能够显示出边框线。
创建每一个xaml页面时必须添加一个布局面板。所有其他UI元素必须放在布局面板中。