简体   繁体   中英

Does ListBox keep the CollectionViewSource per ItemsSource?

I'm writing a control to explore a tree structure which can be dynamically created. This controls looks a lot like an explorer window, with a "CurrentItem" being the opened folder, some "ChildrenItems" being subfolders or files.

To display the ChildrenItems, I'm using a ListBox. When I click on a Child Item, I set the new CurrentItem to be the child Item, and update the ChildrenItems (going down the tree).

So technically, I often modify the ItemsSource property of the ListBox.

I also have some standard commands like "Go Up", "Go Back", "Root", etc

I have had some problem with the "Go Up" command, and noticed that when I change the ItemsSource property of the listbox to an ItemsSource I previoulsy set, the SelectedItem of the ListBox is reset to the old item selected when the old ItemsSource was used.

Maybe a little exemple would be more explicit : Let's say I have this tree structure :

 - Root
   - Node 1
     - SubNode 1a
     - SubNode 1b
   - Node 2
   - Node 3

I begin exploring this structure by setting the "CurrentItem" as the Root. This mean that my ListBox ItemsSource is set to "Node1,Node2,Node3".

I then click on the "Node1" (which changes the SelectedItem). My Control then set its "CurrentItem" to this new SelectedItem, and also set the ListBox ItemsSource to "SubNode1a, SubNode1b".

After that, if I use my "Go Up" command, the "CurrentItem" is reset to "Root", and the ListBox ItemsSource to "Node1,Node2,Node3", but there is a difference : The "Node1" is selected.

This makes me think of a CollectionViewSource which is reused, therefore keeping the selected item. Is this possible?

Thanks for your insights.

I found an interesting article from Bea Stollnitz where she says :

CollectionViewSource also enables another interesting scenario. If a particular CollectionViewSource points to different collections at different times, it remembers all the views that it created to wrap those collections. If a source that has already been set in the past is set again, CVS recognizes it and reuses the view it created originally. This behavior is useful in hierarchical binding scenarios.

That may be the answer I was looking for. My next question is then : Is it possible to disable this behavior?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM