如何:将网格用于自动布局

此示例介绍如何在自动布局方法中使用网格来创建可本地化的应用程序。

用户界面(UI)的本地化可能是一个耗时的过程。 本地化人员通常除了翻译文本之外,还需要重新调整元素的大小和重新定位元素。 在过去,UI 的每种语言都经过了必要的调整。 现在,借助 Windows Presentation Foundation(WPF)的功能,可以设计可减少调整需求的元素。 被称为auto layout的方法是编写那些更容易调整大小和重新定位的应用程序。

以下可扩展应用程序标记语言(XAML)示例演示如何使用网格定位某些按钮和文本。 请注意,单元格的高度和宽度设置为 Auto;因此,包含具有图像的按钮的单元格将调整以适应图像。 Grid由于该元素可以调整其内容,因此,当采用自动布局方法来设计可本地化的应用程序时,它非常有用。

示例:

以下示例演示如何使用网格。

<Grid Name="grid" ShowGridLines ="false">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>

<TextBlock Margin="10, 10, 5, 5" Grid.Column="0" Grid.Row="0" FontSize="24">Grid
</TextBlock>
<TextBlock Margin="10, 10, 5, 5" Grid.Column="0" Grid.Row="1" FontSize="12"  
    Grid.ColumnSpan="2">The following buttons and text are positioned using a Grid.
</TextBlock>  
<Button Margin="10, 10, 5, 5" Grid.Column="0" Grid.Row="2" Background="Pink" 
    BorderBrush="Black" BorderThickness="10">Button 1
</Button>
<TextBlock Margin="10, 10, 5, 5" Grid.Column="1" Grid.Row="2" FontSize="12" 
   VerticalAlignment="Center" TextWrapping="WrapWithOverflow">Sets the background 
   color.
</TextBlock>  
<Button Margin="10, 10, 5, 5" Grid.Column="0" Grid.Row="3" Foreground="Red">
   Button 2
</Button>
<TextBlock Margin="10, 10, 5, 5" Grid.Column="1" Grid.Row="3" FontSize="12" 
   VerticalAlignment="Center" TextWrapping="WrapWithOverflow">Sets the foreground 
   color.
</TextBlock>  
<Button Margin="10, 10, 5, 5" Grid.Column="0" Grid.Row="4">
   <Image Source="data\flower.jpg"></Image>
</Button>
<TextBlock Margin="10, 10, 5, 5" Grid.Column="1" Grid.Row="4" FontSize="12" 
   VerticalAlignment="Center" TextWrapping="WrapWithOverflow">Adds an image as 
   the button's content.
</TextBlock>
</Grid>

下图显示了代码示例的输出。

网格示例
网格

另请参阅