I'm experiencing an issue with a Treeview that is driving me crazy!!!
My TreeView is databound to an object model that is 3 levels deep, and uses a HierarchicalDataTemplate to define what should be displayed for each level:
Company
+-Branch
--+--Contact
I want to make a specific contact the selected node, which I'm doing like this (contact is the object from the databound object model):
Dim companyTreeViewItem As TreeViewItem = Me.AgentTreeView.ItemContainerGenerator.ContainerFromItem(contact.Branch.Company)
Dim branchTreeViewItem As TreeViewItem = companyTreeViewItem.ItemContainerGenerator.ContainerFromItem(contact.Branch)
Dim contactTreeViewItem As TreeViewItem = branchTreeViewItem.ItemContainerGenerator.ContainerFromItem(contact)
If I expand the treeview so the node that is going to be selected is visible (and then go and select something else) this code works, however if I run it before I expand any nodes branchTreeViewItem comes back as Nothing (null).
Any ideas how I can get to the TreeViewItem for my contact object and set it as selected?
EDIT
The code that populates the treeview is just setting the DataContext of the control:
Me.DataContext = New ObjectModel.ObservableCollection(Of DAL.Company)(From c In entities.Companies.Include("Branches").Include("Branches.Contacts") Order By c.CompanyName)
The treeview then has a simple binding
<TreeView ItemsSource="{Binding}" VirtualizingStackPanel.IsVirtualizing="False" >