Search code examples
xamluwp

Slow expanding and collapsing TreeView nodes


When a node in TreeView contains many elements, like above 2000, its expanding and collapsing is very slow. For ListView I was using incremental loading:

<ListView
   Width="500"
   MaxHeight="400"
   IsItemClickEnabled = "False"
   SelectionMode ="None"
   IncrementalLoadingThreshold="5"
   IncrementalLoadingTrigger="Edge"
   ScrollViewer.VerticalScrollBarVisibility="Visible"
   ScrollViewer.VerticalScrollMode="Enabled"/>

However I do not see such option for TreeView. How this can be optimized?


Solution

  • Slow expanding and collapsing TreeView nodes

    Both TreeView and TreeViewItem do not contain IncrementalLoading behavior, so you can't make increment loading for treeview. But you could porcess data soure with linq select-take method to implement Incremental loading function.

    placing a button in the last TreeViewItem that used to load more items.

    For example

    <DataTemplate x:Key="FileTemplate" x:DataType="local:ExplorerItem">
        <TreeViewItem AutomationProperties.Name="{x:Bind Name}" IsSelected="{x:Bind IsSelected,Mode=TwoWay}">
            <StackPanel Orientation="Horizontal">
                <Image Width="20" Source="../Assets/file.png" />
                <TextBlock Margin="0,0,10,0" />
                <TextBlock Text="{x:Bind Name}" />
                <Button Background="White" Margin="15,0,0,0" x:Name="LoadMore"  Visibility="{Binding IsLastItem}" 
                        Command="{Binding  LoadMoreCommand}" CommandParameter="{Binding}">
                    <SymbolIcon Symbol="More"/>
                </Button>
            </StackPanel>
        </TreeViewItem>
    </DataTemplate>
    

    Code Behind

    WeakReferenceMessenger.Default.Register<object>(this, (s, e) =>
    {
        var temp = subitems.Skip(subitems.IndexOf(e as ExplorerItem)+1).Take(20);
        (e as ExplorerItem).IsLastItem = false;
        foreach (var item in temp)
        {            
            folder1.Children.Add(item);
        }
        folder1.Children.Last().IsLastItem = true;
    
    });
    

    enter image description here

    For complete code, please refer to this link.