UWP WinUI TreeView 以编程方式滚动到项目

Posted

技术标签:

【中文标题】UWP WinUI TreeView 以编程方式滚动到项目【英文标题】:UWP WinUI TreeView programatically scroll to item 【发布时间】:2019-01-31 14:23:15 【问题描述】:

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

我找不到这样做的方法。

【问题讨论】:

【参考方案1】:

目前,TreeView 类中没有用于滚动到视图中的此类 api。但是您可以在 TreeView ControlTemplate 中获得 TreeViewList。它基于包含ScrollIntoView 方法的ListViewBase。要获取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());

【讨论】:

以上是关于UWP WinUI TreeView 以编程方式滚动到项目的主要内容,如果未能解决你的问题,请参考以下文章

WinUI 3.0 - 为啥 UWP 项目要求 MS Edge for Business 用于 WebView2

将新项目添加到绑定的 ItemsSource 时,WinUI 3 UWP TabView 不显示新选项卡

UWP C# WINUI NavigationView 如何访问其他页面/视图

类似 UWP 的桌面应用程序

微软宣布 WinUI 的重心在于 Win32,而 UWP 还有未来吗?

如何以编程方式选择 WPF TreeView 中的项目?