Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UWP WinUI TreeView programatically scroll to item

Tags:

uwp

winui

I am trying to use new WinUI toolkit TreeView control. I need to scroll programmatically to specific item.

I cannot find way to do this.

like image 489
user1744147 Avatar asked Jun 24 '26 22:06

user1744147


1 Answers

Currently, The is no such api in TreeView class that used to scroll into view. But you could get TreeViewList in TreeView ControlTemplate. And it is based on ListViewBase that contains ScrollIntoView method. For getting TreeViewList you could use VisualTreeHelper class.

public static DependencyObject FindChildByName(DependencyObject parant, string  ControlName)
{
    int count = VisualTreeHelper.GetChildrenCount(parant);

    for (int i = 0; i < count; i++)
    {
        var MyChild = VisualTreeHelper.GetChild(parant, i);
        if (MyChild is FrameworkElement && ((FrameworkElement)MyChild).Name == ControlName)
            return MyChild;

        var FindResult = FindChildByName(MyChild, ControlName);
        if (FindResult != null)
            return FindResult;
    }
    return null;
}

And the TreeViewList name is ListControl in the TreeView style.

<TreeViewList x:Name="ListControl" AllowDrop="False" 
              CanReorderItems="False" 
              CanDragItems="False" 
              ItemContainerStyle="{StaticResource TreeViewItemStyle}" 
              ItemTemplate="{StaticResource CultureItemDataTemplate}">
    <TreeViewList.ItemContainerTransitions>
        <TransitionCollection>
            <ContentThemeTransition/>
            <ReorderThemeTransition/>
            <EntranceThemeTransition IsStaggeringEnabled="False"/>
        </TransitionCollection>
    </TreeViewList.ItemContainerTransitions> 
</TreeViewList>

Usage

private void Button_Click(object sender, RoutedEventArgs e)
{
    var listControl = FindChildByName(treeView1, "ListControl") as ListViewBase;
    listControl.ScrollIntoView(treeView1.RootNodes.LastOrDefault());
}
like image 102
Nico Zhu - MSFT Avatar answered Jun 27 '26 11:06

Nico Zhu - MSFT