WPF Virtualized TreeView with different orientatio

2019-02-25 10:10发布

问题:

I have a TreeView in XAML with multiple layers. Using this solution I can get a XAML-configured look for each of the different layers, and confirmed that it is UI virtualizing.

However, when I switch a particular layer's VirtualizingStackPanel to have a different Orientation (it doesn't matter whether through code like this solution, or with Snoop) than its parent, then UI virtualization switches off and the TreeView realizes all the TreeViewItems as soon as I expand that layer.

While researching this behavior I noticed that within the reference source for VirtualizingStackPanel as you drill into its MeasureOverride function, you find this comment on line 2116:

Compute if this panel is different in orientation that (sic) either its parent or descendents

It appears that Microsoft has intentionally disabled UI virtualization for this case. So I have two questions:

  • Why does it matter to have orientation consistency between layers?
  • How can I get UI virtualization to work with a TreeView having different orientations within it?

回答1:

UI Virtualization relies on the ability to correctly measure the viewport and the contents that should be in view. Generally speaking, that works out well if you're scrolling in one dimension for a list-like structure (thinking of the tree view as, say, an indented list as far as rendering goes). It doesn't work out as well if you suddenly have to calculate that in two dimensions, depending on which child you're rendering. Think of what the algorithm has to work through if one of those horizontally oriented children is taller than others, but isn't currently visible on the screen - how does it determine if the next vertical child should be in view or not without calculating the layout for all of those children, thus defeating the purpose of virtualization?