商讯信箱
用户名: @
密  码:   注册|忘记密码
登录
个人用户经销商
您的位置:首页 > 技术频道 > 正文

使用Grid来对WPF页面进行布局排版

作者:蝈蝈俊  2007-08-31
    使用Grid布局控件的时候,一些知识点如下:

    我们可以通过定义Grid的ColumnDifinitions和RowDifinitions来实现对于表格的定义,然后根据Grid.Column和Grid.Row的对象来制定位置的方式实现布局。

    比如上面XAML文件中
<Grid > <Grid.ColumnDefinitions> <ColumnDefinition Width="150"/> <ColumnDefinition Width="5" /> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="35"/> <RowDefinition Height="*"/> <RowDefinition Height="35"/> </Grid.RowDefinitions>
    就定义了一个三行三列的表格。

    ColumnDefinition 和 RowDefinition 分别只需要定义 Width 和 Height

    如果我们希望列的宽度或者行的高度是根据内部元素来决定的,我们可以定义为 Auto, 如果我们希望某列或者某行的宽度或者告诉是整体的其他部分,则可以定义成 *,如果我们希望其中一项的长度是另外一项的5倍,则可以一个定义成*,一个定义成5* 。

    我们看 ColumnDefinition 或者 RowDefinition 的 Width 或者 Height 属性的时候,我们可以看到这个属性不是 int或者 double 类型,而是 GridLength 类型。

    下面一个简单的Grid定义来演示上面定义长度的几种写法 
<Window x:Class="WpfApplication1.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300"> <Grid > <Grid.ColumnDefinitions> <ColumnDefinition Width="30"/> <ColumnDefinition Width="auto" /> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="2*" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <Label Grid.Column="0" Grid.Row="0" Background="RosyBrown" ></Label> <Label Grid.Column="1" Grid.Row="0" Background="SkyBlue" >1234567890</Label> <Label Grid.Column="2" Grid.Row="0" Background="Red" ></Label> <Label Grid.Column="0" Grid.Row="1" Background="SpringGreen" ></Label> <Label Grid.Column="1" Grid.Row="1" Background="RoyalBlue" >abc</Label> <Label Grid.Column="2" Grid.Row="1" Background="Violet" ></Label> </Grid> </Window>
    这个XAML文件的效果图如下:


    此外,我们还可以使用 Grid.ColumnSpan Grid.RowSpan 来实现一块布局跨多个表格项的情况。

    小结:

    我个人觉得,把一个窗体或者页面用表格拆分,然后我们在每个表格项中增加我们规划好的控件,这种布局方案在没有比较好的美术细胞下,比较容易做出一个至少不难看的页面布局。

    基于以上的考虑,我觉得我们技术人员开发一些WPF窗体或者页面的时候,Grid控件应该是我们最常用到的。也应该是最应该掌握的控件。
1 2
【内容导航】
第1页: 布局产生困惑 第2页: Grid布局控件
©版权所有。未经许可,不得转载。
[责任编辑:振宇]
[an error occurred while processing this directive]