VirtualizingStackPanel on a Treeview ist not Virtu

2020-07-20 19:24发布

问题:

I've got a problem here, I want to show some items in a TreeView, about 100.000 Elements. If i use the default WPF TreeView everything seems to work, but if i use a custom-TreeView (which is at the moment only an ItemsControl), virtualization doesn't seem to work anymore. While researching over the web, I've tried some solutions but none of them seems to work... Here's my xaml:

<Style TargetType="{x:Type my:MultiSelectionTreeView}">
    <Setter Property="TreeView.Background" Value="Transparent"/>
    <Setter Property="VirtualizingStackPanel.IsVirtualizing" Value="True"/>
    <Setter Property="VirtualizingStackPanel.VirtualizationMode" Value="Recycling"/>
    <Setter Property="TreeView.OverridesDefaultStyle" Value="True" />
    <Setter Property="ItemsControl.ItemsPanel">
        <Setter.Value>
            <ItemsPanelTemplate>
                <VirtualizingStackPanel IsItemsHost="True"/>
            </ItemsPanelTemplate>
        </Setter.Value>
    </Setter>
    <Setter Property="TreeView.Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type my:MultiSelectionTreeView}">
                <Border Background="{TemplateBinding Background}"
                    BorderBrush="{TemplateBinding BorderBrush}"
                    BorderThickness="{TemplateBinding BorderThickness}">
                    <ScrollViewer Focusable="True" CanContentScroll="true" 
                                  Padding="4" 
                                  VerticalScrollBarVisibility="Auto">
                        <ItemsPresenter HorizontalAlignment="Stretch"/>
                    </ScrollViewer>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

The Items are in an ObservableCollection with DataBinding, so that shouldn't be the Problem... but what is it???

Greets,

Jürgen

回答1:

The VirtualizingStackPanel has some special code that looks for TreeView and TreeViewItem. In addition, TreeViewItem implements VirtualizingStackPanel.IProvideStackingSize, which is a internal interface which you won't be able to implement.

So if you are trying to replicate the hierarchical structure of items like in the TreeView, then you'd have to derive from TreeView to use virtualization (not ItemsControl).