你好,欢迎来到电脑编程技巧与维护杂志社! 杂志社简介广告服务读者反馈编程社区  
合订本订阅
 
 
您的位置:技术专栏 / Linux开发
使用Grid来对WPF页面进行布局排版(2)
 
我们可以通过定义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来对WPF页面进行布局排版

  图2

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

  小结

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

  基于以上的考虑,我觉得我们技术人员开发一些WPF窗体或者页面的时候,Grid控件应该是我们最常用到的。也应该是最应该掌握的控件。

(编辑:aniston)

  推荐精品文章

·2024年12月目录 
·2024年11月目录 
·2024年10月目录 
·2024年9月目录 
·2024年8月目录 
·2024年7月目录 
·2024年6月目录 
·2024年5月目录 
·2024年4月目录 
·2024年3月目录 
·2024年2月目录 
·2024年1月目录
·2023年12月目录
·2023年11月目录

  联系方式
TEL:010-82561037
Fax: 010-82561614
QQ: 100164630
Mail:gaojian@comprg.com.cn

  友情链接
 
Copyright 2001-2010, www.comprg.com.cn, All Rights Reserved
京ICP备14022230号-1,电话/传真:010-82561037 82561614 ,Mail:gaojian@comprg.com.cn
地址:北京市海淀区远大路20号宝蓝大厦E座704,邮编:100089