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.
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());
}