WPF中的Grid网格布局
开发工具与关键技术:Visual Studio 2015、WPF
作者:黄元进
撰写时间:2019年4月24日
要使用Grid,首先要向RowDefinitions和ColumnDefinitions属性中添加一定数量的RowDefinitions和 ColumnDefinitions元素,从而定义行数和列数。而放置在Grid面板中的控件元素都必须显示采用Row和Column附加属性定义其放置所在的行和列,这里我定义了一个两行两列的Grid,在每一个单元格里面放置一个Button按钮。
使用XAML代码实现:
<Window x:Class="Wpf动画.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
WindowStartupLocation="CenterScreen"
Title="MainWindow" Height="350" Width="525">
<!--定义网格,此处显示了网格线-->
<Grid ShowGridLines="False">
<!--自定义行-->
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<!--自定义列-->
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Button Background="DarkBlue" Foreground="LawnGreen" Content="鸣" />
<Button Grid.Column="1" Grid.Row="1" Background="Khaki" Foreground="DarkRed" Content="の"/>
<Button Grid.Column="2" Grid.Row="2" Background="NavajoWhite" Foreground="SkyBlue" Content="人" />
<Button Background="ForestGreen" Foreground="Gainsboro" Grid.Column="2" Content="佐"/>
<Button Background="Black" Content="助" Foreground="BurlyWood" Grid.Row="2"/>
</Grid>
</Window>
在按钮里,设置了一些基础的属性,比如Background—背景色,Foreground—字体颜色,使用Grid.Column和Grid.Row两个属性来调整位置。
呈现的效果图如下: