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

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

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

以下 Extensible Application Markup Language (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>

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

Grid example
Grid

另请参阅