Search code examples
wpftreeviewvirtualizationui-virtualization

WPF : TreeView virtualization not working


What can stop a TreeView from virtualizing if the TreeView is set up as follows?

<TreeView 
    ItemsSource="{Binding}" 
    VirtualizingStackPanel.IsVirtualizing="True">
    <TreeView.ItemsPanel>
        <ItemsPanelTemplate>
            <VirtualizingStackPanel />
        </ItemsPanelTemplate>
    </TreeView.ItemsPanel>
    <TreeView.ItemContainerStyle>
        <Style
            TargetType="{x:Type TreeViewItem}">
            <Setter
                Property="IsExpanded"
                Value="{Binding IsExpanded, Mode=TwoWay}"/>
        </Style>
    </TreeView.ItemContainerStyle>
</TreeView>

I have one that is not virtualizing, when i expand the nodes (and use snoop to check) i have all of the TreeViewItems being created. I am wondering if there is some combination of containers that would prevent the TreeView from virtualizing its content. (like hosting it in a StackPanel for example)


Solution

  • The problem was with the styling. After some research we found that there was an unnamed style targeting the TreeView (i.e. one with DataType={x:Type TreeView} without an x:Key) and one targetting the TreeViewItem in our App.xaml (or equivalent) It was overriding the ControlTemplate for each respectively.

    These styles did not have the triggers to set the ItemsPanel to a VirtualizingStackPanel and had no mention of any virtualization. When the styles are removed the TreeView works fine. Even though the local properties set the ItemsPanel and the VirtualizingStackPanel.Isvirtualizing="True" on the TreeView these properties were not being propogated to the TreeViewItems so the top level of the TreeView would virtualize whilst the sub categories would not (as their virtualization behaviour was dependant on the TreeViewItem)