UserControls上的焦点和TabIndex

时间:2011-10-31 21:31:27

标签: wpf user-controls focus

我有一个奇怪的行为: 我有一个包含文本框和(简单)用户控件(文本框和按钮)的MainWindow,但我将其剥离为仅用于调试目的的文本框。

当我使用textboxes和usercontrols而不设置TabIndex属性时,光标以正确的顺序逐步浏览控件(按控件添加到窗口的顺序)

当我使用textboxes和usercontrols WITH设置TabIndex属性时,光标以无效顺序(首先是所有用户控件,然后是所有文本框)逐步执行控件,当TabIndex设置为对应于其中的顺序的值时,这也是如此控件已添加

这是我的usercontrol

<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导致订单000000,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导致订单000000,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中以“正确”的顺序添加控件?

此致 克劳斯

1 个答案:

答案 0 :(得分:28)

默认情况下,WPF在同一选项卡级别读取UserControls内部和外部的所有控件(除非另有说明)。由于UserControl中的控件没有指定TabIndex,因此它们会在第一个制表符循环后标记为最后一个。

要更改此行为,我通常在UserControl定义上设置IsTabStop="False",然后将内部控件TabIndex绑定到UserControl的TabIndex

UserControl 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上的KeyboardNavigation.TabNavigation附加属性设置为Local来正确显示标签。我似乎记得有这个问题,但老实说我不记得细节,所以它可能会有用。

<UserControl x:Class="SmallControl" ...
             KeyboardNavigation.TabNavigation="Local"  />
相关问题