1
votes

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" >
1
Would you mind posting the code that populates the TreeView?louisgab
@louisgab, I've updated the post to include the code that is populating the TreeView.Darren

1 Answers

3
votes

The proper solution would be to use MVVM and create a view model for each item in the TreeView with IsSelected and IsExpanded properties bound to the corresponding TreeViewItem properties. Then you will be able to manipulate the IsExpanded and IsSelected states without having to dial with item containers generators.

But also you could do the following (sorry, my code will be in C#):

TreeViewItem companyTreeViewItem = (TreeViewItem)AgentTreeView.ItemContainerGenerator.ContainerFromItem(contact.Branch.Company);
companyTreeViewItem.IsExpanded = true;

companyTreeViewItem.ItemContainerGenerator.StatusChanged += (o, e) => {
    if (companyTreeViewItem.ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated) 
    {
        TreeViewItem branchTreeViewItem = (TreeViewItem) companyTreeViewItem.ItemContainerGenerator.ContainerFromItem(contact.Branch);
        branchTreeViewItem.IsExpanded = true;

        branchTreeViewItem.ItemContainerGenerator.StatusChanged += (o1, e1) => {
            if (branchTreeViewItem.ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated) 
            {
                TreeViewItem contactTreeViewItem = (TreeViewItem) branchTreeViewItem.ItemContainerGenerator.ContainerFromItem(contact);
                contactTreeViewItem.IsSelected = true;
            }
        };
    }
};