Tab does not work for text fields inside data template

I am writing a very simple name / value editing tool where the value is editable - the label on the left and the property text box on the right. The control works fine, except when the user presses TAB when the β€œvalue” on the right is inside one of the text boxes, the focus shifts from my control to the next control in hiearchy. I want the focus to move to the next text field in my control so that users can simply insert tabs between property text fields. I tried setting "IsTabStop" to true, but it doesn't seem to work.

Here is my data pattern:

    <DataTemplate x:Key="myDataTemplate">
        <StackPanel>
            <TextBlock Text="{Binding Name}" />
            <TextBox IsTabStop="True" Text="{Binding Value, Mode=TwoWay}" />
        </StackPanel>
    </DataTemplate>
+3
source share
1 answer

Do you use your data template as an element template for an element container control, for example. Listbox Take a look at the KeyboardNavigation class , you can set its TabNavigation property to Continue or Loop for the container of your elements, smth for example:

<ListBox x:Name="myListBox"
    KeyboardNavigation.TabNavigation="Continue"
    ItemTemplate="{StaticResource myDataTemplate}" 
...

when the focus is changed using the tab key in the ListBox, the focus will move from each item, and when the last item is reached, the focus will return to the first item "Loop" or move to the next custom control in the form if "Continue".

hope this helps, believes

edit0:

<ListBox x:Name="myListBox"
    KeyboardNavigation.TabNavigation="Continue"
    ItemTemplate="{StaticResource myDataTemplate}" 
    SelectionChanged="testList_SelectionChanged"
...
/>
private void testList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    Dispatcher.BeginInvoke(DispatcherPriority.Normal, new ThreadStart(() =>
    {
        ListBoxItem item = testList.ItemContainerGenerator.ContainerFromIndex(testList.SelectedIndex) as ListBoxItem;
        if (item != null)
        {
            TextBox textBox = GetDescendantTextBox(item) as TextBox;
            if (textBox != null) textBox.Focus();
        }
    }));
}

public static Visual GetDescendantTextBox(Visual element)
{
    if (element == null) return null;
    if (element is TextBox) return element;
    Visual result = null;
    if (element is FrameworkElement)
        (element as FrameworkElement).ApplyTemplate();
    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(element); i++)
    {
        Visual visual = VisualTreeHelper.GetChild(element, i) as Visual;
        result = GetDescendantTextBox(visual);
        if (result != null) break;
    }
    return result;
}
+4

Source: https://habr.com/ru/post/1726760/


All Articles