下面是一個簡單的Grid控件的范例:
<Window
XMLns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
XMLns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Programming .Net 3.5 | Understanding Grids">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock TextBlock.FontSize="36"
TextBlock.Foreground="White"
Background="Blue"
Grid.Column="0"
Grid.Row="0"
Grid.RowSpan="2">1</TextBlock>
<TextBlock TextBlock.FontSize="36"
Background="Gold"
Grid.Column="1"
Grid.Row="0" >2</TextBlock>
<TextBlock TextBlock.FontSize="36"
TextBlock.Foreground="White"
Background="Crimson"
Grid.Column="2"
Grid.Row="0" >3</TextBlock>
<TextBlock TextBlock.FontSize="36"
Background="White"
Grid.Column="1"
Grid.Row="1"
Grid.ColumnSpan="2">4</TextBlock>
<TextBlock TextBlock.FontSize="36"
TextBlock.Foreground="White"
Background="Purple"
Grid.Column="0"
Grid.Row="2" >5</TextBlock>
<TextBlock TextBlock.FontSize="36"
TextBlock.Foreground="White"
Background="Green"
Grid.Column="1"
Grid.Row="2" >6</TextBlock>
<TextBlock TextBlock.FontSize="36"
TextBlock.Foreground="White"
Background="Black"
Grid.Column="2"
Grid.Row="2" >7</TextBlock>
</Grid>
</Window>
在Kaxaml 工具中的演示效果如下:
本范例代碼首先定義一個Grid 元素,接著分別定義三個 RowDefinitions 和 ColumnDefinitions。接下來逐個定義TextBox元素:
<TextBlock TextBlock.FontSize="36"
TextBlock.Foreground="White"
Background="Blue"
Grid.Column="0"
Grid.Row="0"
Grid.RowSpan="2">1</TextBlock>
FontSize 指定字體大小,Foreground 指定文字顏色,Column和Row 屬性分別指定列、行位置坐標,RowSpan 與 Html 基本一致,表示占用多少行,類似的一個屬性是ColumnSpan。
有趣的是,Grid 控件自身沒有顏色,Grid中的TextBlocks 控件提供顏色,Grid僅僅提供結構定義。