TOC

This article has been localized into Chinese by the community.

控件概念:

Tab顺序

如果您为了学习编程而使用了计算机足够长时间,您也许知道可以使用键盘上的Tab按键以在窗口/对话框间切换。这使得您可以在填写表格或执行其他类似事情时双手不需要离开键盘,而不是使用鼠标选择下一个控件。

WPF直接支持这种行为,甚至更好:它将自动建立从一个字段移动到另一个字段时使用的顺序,因此通常,您根本不必担心这一点。 但是,有时窗口/对话框的设计会导致WPF使用您可能不同意的Tab键顺序,原因有多种。 此外,您可以决定某些控件不应该是Tab键顺序的一部分。 请允许我用一个例子来说明这一点:

此对话框包含一个从中间分隔的Grid控件,两边各有一个包含有Label控件和TextBox控件的StackPanel控件。默认的Tab键顺序从该窗口的第一个控件开始,然后依次为其内部的子控件,最后跳转至下一个控件。由于对话框包含有纵向的StackPanel控件,意味着顺序是从First name部分开始,然后是Street name部分,然后是City部分,最后才是第二个包含有Last nameZip code部分的StackPanel控件。当Tab键离开第二个StackPanel后,才是两个按钮。

但是,对于此对话框,这不是我想要的行为。 相反,我想使用Tab从First nameLast name(所以基本上是水平移动而不是垂直移动),最重要的是,我不希望使用Tab进入City字段,因为将自动填写在这个假设的对话框中的Zip code上,因此已经只读了。 为了完成所有这些,我将使用两个属性:TabIndexIsTabStop。 TabIndex用于定义顺序,而IsTabStop属性将强制WPF在这个窗口按Tab时跳过这个控件。 这是用于创建对话框的标记:

<Window x:Class="WpfTutorialSamples.Control_concepts.TabOrderSample"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfTutorialSamples.Control_concepts"
mc:Ignorable="d"
Title="TabOrderSample" Height="250" Width="400">
    <Grid Margin="20">
<Grid.ColumnDefinitions>
    <ColumnDefinition Width="*" />
    <ColumnDefinition Width="20" />
    <ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
    <RowDefinition Height="*" />
    <RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<StackPanel>
    <Label>First name:</Label>
    <TextBox TabIndex="0" />
    <Label>Street name:</Label>
    <TextBox TabIndex="2" />
    <Label>City:</Label>
    <TextBox TabIndex="5" IsReadOnly="True" IsTabStop="False" Background="Gainsboro" />
</StackPanel>
<StackPanel Grid.Column="2">
    <Label>Last name:</Label>
    <TextBox TabIndex="1" />
    <Label>Zip Code:</Label>
    <TextBox TabIndex="4" />
</StackPanel>
<Button Grid.Row="1" HorizontalAlignment="Right" Width="80">Add</Button>
<Button Grid.Row="1" Grid.Column="2" HorizontalAlignment="Left" Width="80">Cancel</Button>
    </Grid>
</Window>

注意我如何简单地为每个相关控件的TabIndex属性提供一个数字,然后指定City的TextBox的IsTabStop属性 - 在对话框中控制Tab键顺序就这么简单!

小结

控制对话框的Tab键顺序非常重要,但幸运的是,WPF可以很好地为您自动定义正确的Tab键顺序。 但是,在某些情况下,使用TabIndexIsTabStop属性进行控制是有意义的,如上例所示。


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!