我有这样的树视图
<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>
绑定TreeItems是一个ObservableCollection。
如果这棵树不是很大,这很好用但是如果我有很多文件夹/子文件夹结构,它可能需要10秒左右才能加载。
如何解决问题,以便更快地构建树?
答案 0 :(得分:1)
延迟加载可以如下所述完成。由于发布任何链接都不是好习惯。我在链接中发布链接和代码内容。
我从这里得到了它。 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;
}
}