我有一个奇怪的行为:我有一个包含文本框和(简单的)用户控件(文本框和按钮)的MainWindow,但我为了调试的目的,将其剥离为只有一个文本框。
当我在没有设置TabIndex属性的情况下使用文本框和用户控件时,光标按照正确的顺序(按照控件添加到窗口的顺序)在控件中移动。
当我在设置TabIndex属性的情况下使用文本框和用户控件时,光标会以无效的顺序(先是所有的用户控件,然后是所有的文本框),当TabIndex被设置为与控件添加顺序相对应的值时也是如此。
这是我的用户控制
<UserControl x:Class="SmallControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
>
<TextBox x:Name="txTEXT" Text="{Binding Text}" />
</UserControl>
下面的Mainwindow xaml导致的顺序是00000000,111111,222222,333333,这是确定的。
<GroupBox Header="Small,Textbox,Small,TextBox without TabIndex">
<UniformGrid Columns="4">
<local:SmallControl Text="000000" />
<TextBox Text="111111" />
<local:SmallControl Text="222222" />
<TextBox Text="333333" />
</UniformGrid>
</GroupBox>
下面的Mainwindow xaml导致顺序0000,222222,111111,333333,那是不确定的。
<GroupBox Header="Small,Textbox,Small,TextBox with TabIndex">
<UniformGrid Columns="4">
<local:SmallControl TabIndex="0" Text="000000" />
<TextBox TabIndex="1" Text="111111" />
<local:SmallControl TabIndex="2" Text="222222" />
<TextBox TabIndex="3" Text="333333" />
</UniformGrid>
</GroupBox>
有什么方法可以使用TabIndex而不需要在XAML中以 "正确 "的顺序添加控件?
默认情况下,WPF在同一标签级别读取所有控件,包括UserControls内部和外部的控件(除非另有规定)。由于UserControl内部的控件没有指定TabIndex,所以在第一个标签周期后,它们会被标签化到最后。
为了改变这种行为,我通常将 IsTabStop="False"
然后我将内部控件TabIndex绑定到UserControl的TabIndex上。
用户控制XAML
<TextBox x:Name="txTEXT" Text="{Binding Text}"
TabIndex="{Binding Path=TabIndex, RelativeSource={RelativeSource
AncestorType={x:Type local:SearchView}}}"/>
XAML用法
<GroupBox Header="Small,Textbox,Small,TextBox with TabIndex">
<UniformGrid Columns="4">
<local:SmallControl TabIndex="0" Text="000000" IsTabStop="False" />
<TextBox TabIndex="1" Text="111111" />
<local:SmallControl TabIndex="2" Text="222222" IsTabStop="False" />
<TextBox TabIndex="3" Text="333333" />
</UniformGrid>
</GroupBox>
您也可以通过设置下面的选项来让它正确地分页。键盘导航.标签导航 在您的UserControl上附加的属性为 本地. 我似乎记得有这个问题,但我老实说不记得细节了,所以它可能会工作。
<UserControl x:Class="SmallControl" ...
KeyboardNavigation.TabNavigation="Local" />