I have a virtualized TreeView that I was building "manually" by creating a stack panel and using .Add for each item. I then had a very simple _TextInput event that was finding the TreeViewItem and passing it to these two clever routines that would bring the item into view. Full disclosure, these are NOT my originals:
Private Function FindVisualChild(Of T As System.Windows.Media.Visual)(ByVal visual As System.Windows.Media.Visual) As T For i As Integer = 0 To VisualTreeHelper.GetChildrenCount(visual) - 1 Dim child As System.Windows.Media.Visual = CType(VisualTreeHelper.GetChild(visual, i), System.Windows.Media.Visual) If child IsNot Nothing Then Dim correctlyTyped As T = TryCast(child, T) If correctlyTyped IsNot Nothing Then Return correctlyTyped End If Dim descendent As T = FindVisualChild(Of T)(child) If descendent IsNot Nothing Then Return descendent End If End If Next Return Nothing End Function Sub BringIntoView(ByVal item As TreeViewItem) Dim parent As ItemsControl = TryCast(item.Parent, ItemsControl) If parent IsNot Nothing Then Dim itemHost As System.Windows.Controls.VirtualizingStackPanel = FindVisualChild(Of System.Windows.Controls.VirtualizingStackPanel)(parent) If itemHost IsNot Nothing Then itemHost.BringIndexIntoViewPublic(parent.Items.IndexOf(item)) item.Focus() End If End If End Sub
(why is the code formatting not working?)
Now that I've bound the data (make the tree load in a fraction of the time) the TreeView.TreeViewItem is the type of my data object and not a TreeViewItem, which is handy elsewhere in the code except that I need the TreeViewItem for these two routines to bring into view the virutualized TreeViewItem.
I've spent considerable time finding all kinds of posts with similar questions but haven't come to any answers that don't involve turn OFF virtualization, which isn't an option due to the number of items in the TreeView. This Microsoft post seems to have the trick where the tree and then it's child items get passed recursively as containers, but that involves traversing the whole tree, which isn't necessary because I know the index I need.
The Note in the post mentions searching the data items then "finding" the corresponding TreeViewItem. Searching my data is the easy part (don't need to search child items) and I know the index of the TreeViewItem I want but I can't work out how to get the actual TreeViewItem object.
Any help would be greatly appreciated.