Search code examples
wpftreeviewtreeviewitemmultibinding

Why TreeViewItems not generated in Multibinding except if visible?


I have A 3 Level TreeView which is using multibinding to generate for every instance of Class A 2 TreeViewItems as List of Class B . And every List contains Items lets say of Class C .

I can add Items of Class C for each List in my UI while the Lists(Class B) are collapsed . I can even add Class C for each List(Class B) while the whole TreeViewItem(Class A) is collapsed .

My Problem is I need to be able to access all TreeViewItems even if they are collapsed.(for ex to select them).

I tried doing so but i encountered following problems :

1- All not visible TreeViewItems(of classes B and C) are not yet created as TreeViewItems.(how can i make them be?)

2- When u expand a Class B TreeViewIiem for the FIRST TIME u get to see all its Items(Class C) as TreeViewItems.(obviously trivial)

3- Collapsing after Expanding any Class B (there are only 2) in a specific Class A TreeViewItem will result in being able to add Class C instances as TreeViewItems even if the whole TreeViewItem(Class A) is collapsed .(As long as u stay in this Class A TreeViewItem)

4- If u change the selected Class A(i.e if u click on another TreeViewItem which has an ancestor of Class A different than the choosen one) all not visible TreeViewItems of previously choosen Class A are lost. and u can begin again by step 1 in the newly choose Class A.

So how can i be able to Select any TreeViewItem of Class C or B at any give moment?

Thank you


Solution

  • to 1) Depending on how many items you want to show in your tree view, you don't want to create all TreeViewItems. What you are observing is called Virtualization. If you really don't want this, and i strongly advise you not to do that, you can use VirtualizingStackPanel.IsVirtualizing="False" on your TreeView. If you don't mind making your hands dirty, this might help aswell.

    Unfortunately i don't understand your other points. First of all, tell us how you create your hierarchy of Data. I guess you could make everything work when using dynamic data and HierarchicalDataTemplate with proper bindings (for collapsing etc.). Because then it doesn't matter what ui control is visible, only the data should be relevant.

    And for your last and actual question. If you use ItemsSource and HierarchicalDataTemplate, you can easyl traverse your data to find your Items and, for example, collapse to make all Class C visible.

    One problem though is, the selection of the TreeView control is a bit problematic. See this article for a way to solve it