pixel
pixel

Reputation: 10547

WPF TreeView Slow Loading

I have a tree view like this

<TreeView x:Name="tvFolders" 
  ItemsSource="{Binding TreeItems}" 
  Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2"
  BorderBrush="{StaticResource ColligoBorderLightBrush}"
  IsTextSearchCaseSensitive="False" 
  IsTextSearchEnabled="True"
  VirtualizingPanel.VirtualizationMode="Recycling"
  VirtualizingPanel.IsVirtualizing="True"
  Loaded="tvFolders_Loaded">

</TreeView>

The binding TreeItems is an ObservableCollection.

If this tree is not very large, this works great but if I have many folders/subfolders structure it can take 10 seconds or so until it loads.

How do I solve the issue so tree is built faster?

Upvotes: 0

Views: 1663

Answers (1)

Ayyappan Subramanian
Ayyappan Subramanian

Reputation: 5366

Lazy loading can be done as mentioned below. Since it not good practice to post any links. I am posting links as well as code content in the link.

I got it from here. http://www.wpf-tutorial.com/treeview-control/lazy-loading-treeview-items/

 <Grid>
    <TreeView Name="trvStructure" TreeViewItem.Expanded="TreeViewItem_Expanded" Margin="10" />
</Grid>

 public partial class LazyLoadingSample : Window
    {
            public LazyLoadingSample()
            {
                    InitializeComponent();
                    DriveInfo[] drives = DriveInfo.GetDrives();
                    foreach(DriveInfo driveInfo in drives)
                            trvStructure.Items.Add(CreateTreeItem(driveInfo));
            }

            public void TreeViewItem_Expanded(object sender, RoutedEventArgs e)
            {
                    TreeViewItem item = e.Source as TreeViewItem;
                    if((item.Items.Count == 1) && (item.Items[0] is string))
                    {
                            item.Items.Clear();

                            DirectoryInfo expandedDir = null;
                            if(item.Tag is DriveInfo)
                                    expandedDir = (item.Tag as DriveInfo).RootDirectory;
                            if(item.Tag is DirectoryInfo)
                                    expandedDir = (item.Tag as DirectoryInfo);
                            try
                            {
                                    foreach(DirectoryInfo subDir in expandedDir.GetDirectories())
                                            item.Items.Add(CreateTreeItem(subDir));
                            }
                            catch { }
                    }
            }

            private TreeViewItem CreateTreeItem(object o)
            {
                    TreeViewItem item = new TreeViewItem();
                    item.Header = o.ToString();
                    item.Tag = o;
                    item.Items.Add("Loading...");
                    return item;
            }
    }

Upvotes: 1

Related Questions