首页 > 解决方案 > UWP WinUI TreeView 以编程方式滚动到项目

问题描述

我正在尝试使用新的WinUI工具包 TreeView控件。我需要以编程方式滚动到特定项目。

我找不到办法做到这一点。

标签: uwpwinui

解决方案


目前,TreeView用于滚动到视图的类中没有这样的 api。但是你可以进入TreeViewListTreeView ControlTemplate。它基于ListViewBase包含ScrollIntoView方法。为了让TreeViewList你可以使用VisualTreeHelper类。

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;
}

TreeViewList 名称是 TreeView 样式中的 ListControl。

<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>

用法

private void Button_Click(object sender, RoutedEventArgs e)
{
    var listControl = FindChildByName(treeView1, "ListControl") as ListViewBase;
    listControl.ScrollIntoView(treeView1.RootNodes.LastOrDefault());
}

推荐阅读