WPF TreeView does not support Data Virtualization

WPF implements UI Virtualization via VirtualizingStackPanel and it works great, but situation with Data Virtualization is a bit more complex.

After doing some experimentation I realized that VirtualizingStackPanel when used with WPF TreeView does not allow the data to be virtualized because it iterates through all the collection of data items from inside its MeasureOverride function. However, it access only visible data items when used with DataGrid or ListView, so it allows to use some paging or caching techniques in this case. See the following articles for more information:

If you interested on what I tried to do with TreeView, please read below.

I replaced VirtualizingStackPanel with Dan Crevier’s VirtualizingTilePanel by overriding TreeViewItem’s PrepareContainerForItemOverride method:

public class AsyncTreeViewItem : TreeViewItem
{
    protected override DependencyObject GetContainerForItemOverride()
    {
        return new AsyncTreeViewItem();
    }

    protected override bool IsItemItsOwnContainerOverride(object item)
    {
        return item is AsyncTreeViewItem;
    }

    protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
    {
        AsyncTreeViewItem tree_view_item = element as AsyncTreeViewItem;

        if (item is Model.CategoryView)
        {
            FrameworkElementFactory factoryPanel = new FrameworkElementFactory(typeof(Controls.VirtualizingTilePanel));
            ItemsPanelTemplate template = new ItemsPanelTemplate();
            template.VisualTree = factoryPanel;
            tree_view_item.ItemsPanel = template;
        }

        base.PrepareContainerForItemOverride(element, item);
    }
}

After playing a bit with VirtualizingTilePanel’s code I made my TreeView work somehow, but it did not scroll correctly and hanged up sometimes. So I think that theoretically, it is possible to use some very smart Panel instead of VirtualizingStackPanel, but in practice it is not a trivial task Улыбка

Leave a Reply

Your email address will not be published. Required fields are marked *