如何:使用网格进行自动布局

更新:2007 年 11 月

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

用户界面 (UI) 的本地化是一个很耗时的过程。通常,本地化人员除了需要翻译文本之外,还需要重新调整元素的大小并重新定位元素。过去,要针对任何一种语言改编 UI 都需要进行调整。现在,使用 Windows Presentation Foundation (WPF) 的功能,您可以对元素进行设计以减少必需的调整工作。这种编写可以更方便地调整大小和重新定位的应用程序的方法称为 automatic 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>

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

网格

网格示例

说明:

有关上述示例所摘自的完整代码示例,请参见可本地化应用程序的网格的示例

请参见

任务

如何:使用自动布局创建按钮

概念

使用自动布局概述