TOC

This article has been localized into Chinese by the community.

面板控件:

使用Grid-联系人窗口

在最后几章中, 我们讨论了很多理论信息, 每个信息都有一些非常理论的例子。在本章中, 我们将把到目前为止学到的关于网格的知识结合到一个可以在现实世界中使用的例子中: 一个简单的contact form。

联系人窗体的好处是, 它只是一个常用对话框的示例-您可以使用使用的技术并将其应用于您需要创建的几乎任何类型的对话框。

第一次完成这项任务非常简单,它将向您展示一个非常基本的联系表格。它使用三行,其中两行具有自动高度,最后一行具有星高,因此它消耗了剩余的可用空间:

<Window x:Class="WpfTutorialSamples.Panels.GridContactForm"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="GridContactForm" Height="300" Width="300">
    <Grid>
		<Grid.RowDefinitions>
			<RowDefinition Height="Auto" />
			<RowDefinition Height="Auto" />
			<RowDefinition Height="*" />
		</Grid.RowDefinitions>		
		<TextBox>Name</TextBox>
		<TextBox Grid.Row="1">E-mail</TextBox>
		<TextBox Grid.Row="2" AcceptsReturn="True">Comment</TextBox>		
	</Grid>
</Window>

如您所见,最后一个TextBox只占用剩余空间,而前两个只占用它们所需的空间。尝试调整窗口大小,您将看到注释TextBox随之调整大小。

在这个非常简单的示例中,没有标签来指定每个字段的用途。相反,解释性文本位于TextBox内部,但这通常不是Windows对话框的外观。让我们尝试一下改善外观和可用性:

<Window x:Class="WpfTutorialSamples.Panels.GridContactFormTake2"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="GridContactFormTake2" Height="300" Width="300">
	<Grid Margin="10">
		<Grid.ColumnDefinitions>
			<ColumnDefinition Width="Auto" />
			<ColumnDefinition Width="*" />
		</Grid.ColumnDefinitions>
		<Grid.RowDefinitions>
			<RowDefinition Height="Auto" />
			<RowDefinition Height="Auto" />
			<RowDefinition Height="*" />
		</Grid.RowDefinitions>
		<Label>Name: </Label>
		<TextBox Grid.Column="1" Margin="0,0,0,10" />
		<Label Grid.Row="1">E-mail: </Label>
		<TextBox Grid.Row="1" Grid.Column="1" Margin="0,0,0,10" />
		<Label Grid.Row="2">Comment: </Label>
		<TextBox Grid.Row="2" Grid.Column="1" AcceptsReturn="True" />
	</Grid>
</Window>

但是可能你有时候也想让评论部分突出, 这时候, 让我们跳过Label并使用ColumnSpan来让评论的TextBox获得更多的空间:

<TextBox Grid.ColumnSpan="2" Grid.Row="2" AcceptsReturn="True" />

如您所见,Grid是一个非常强大的面板。希望您在设计自己的对话框时可以使用所有这些技巧。


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!