Nick Sun
Nick Sun

Reputation: 41

how to find node in WPF treeview?

I use a WPF treeview which contains many items, 1000 for example. The treeview will load very slowly, so I followed microsoft advice from the next link:

http://msdn.microsoft.com/en-us/library/cc716882.aspx

I set VirtualizingStackPanel.IsVirtualizing to "True" and VirtualizingStackPanel.VirtualizationMode to "Recycling". The performance of the treeview is now very good, but one problem occurs.

When I want to find one node in the treeview which is out of the visible nodes,the TreeViewItem will be null. for example, I want to find one node in the top of the treeview when the treeview in the bottom. I want the treeview scroll to the top automatically after I search the node and display the node which need show. How could I do this?

your help is sincerely appreciated!

Upvotes: 1

Views: 2827

Answers (2)

Aleksey
Aleksey

Reputation: 1347

Actually VirtualizingStackPanel does not continiously load elements. Instead, it re-uses the existing elements and replaces the DataContext behind them. If you have an VirtualizingStackPanel with 1000 items for example, and only 20 are visible at a time, but actually it renders littel more items for a scroll buffer.

For example in you situation, you see 20 items and 5 extra items for scroll buffer. When you scroll, the DataContext behind those 20+5 controls gets changed, but the actual controls themselves will never get replaced.

If you do something like enter Value in TreeViewItem #1, and that TreeViewItem.Value is not bound to anything, then the Value will always show up because the control is getting re-used. If you bind the TreeViewItem.Value to a value, then the DataContext will change when you scroll which will replace the displayed Value.

Upvotes: 0

Rohit Vats
Rohit Vats

Reputation: 81323

Since Virtualization is on for your TreeView, itemcontainers (treeViewItem) are not generated for objects which are not visible. That's why you are getting null for your treeviewItem.

If you want to get the treeViewItem, somehow you need to generate containers for underlying object which you can do by calling BringIntoView method.

Detailed explanation can be found here at MSDN with sample.

Upvotes: 1

Related Questions