Search code examples
c#wpftabcontrolscrollviewerstackpanel

ScrollViewer of WPF - How focus content


I have Providing TabControl, on TabControl I have many TabItem, and during each TabItem I have many ScrollViewer, and on each ScrollViewer I have StackPanel

1) When I try to scroll down/up, With mouse -> Scroll works fine

2) When I try to Click on content of StackPanel and touch up/down of keyboard -> Scroll works fine

But I case of changing tabitem of TabControl, I can't use Keyboard(Up/Down),and it's not works.

Am I must to provide .KeyDown+= , and attention which tabItem is active, or I could focus content of tabItem during touching tabItem ?


Solution

  • If I'm reading your question correctly, your view looks something like

    <TabControl>
        <TabItem Header="First tab">
            <ScrollViewer>
                <StackPanel Height="2000"/>
            </ScrollViewer>
        </TabItem>
        <TabItem Header="Second tab">
            <ScrollViewer>
                <StackPanel Height="2000"/>
            </ScrollViewer>
        </TabItem>
    </TabControl>
    

    and you want to set your keyboard focus to the content of the TabItem whenever the selected tab is changed. If so, one possible solution would be to make the contents focusable and explicitly set the keyboard focus whenever the selected tab changes; that is, do something like

    <TabControl SelectionChanged="TabControlSelectionChanged">
        <TabItem Header="First tab">
            <ScrollViewer>
                <StackPanel Height="2000" Focusable="True"/>
            </ScrollViewer>
        </TabItem>
        <TabItem Header="Second tab">
            <ScrollViewer>
                <StackPanel Height="2000" Focusable="True"/>
            </ScrollViewer>
        </TabItem>
    </TabControl>
    

    where TabControlSelectionChanged is given by

    private void TabControlSelectionChanged(object sender, SelectionChangedEventArgs e) =>
        ((e.AddedItems[0] as TabItem)?.Content as ScrollViewer)?.Focus();