Live Chat Icon For mobile
Live Chat Icon

How do I obtain a reference to the child TreeViewItems of a parent TreeViewItem?

Platform: WPF| Category: TreeView

It’s a bit tricky because WPF doesn’t ‘realize’ the child nodes until they get rendered and you will also have to use some not very straight forward APIs to obtain the child. So, you will have to do something like this:

// First set IsExpanded to true.   
tviParent.IsExpanded = true;   
// Then wait for the child items to get generated   
if (tviParent.ItemContainerGenerator.Status != System.Windows.Controls.Primitives.GeneratorStatus.ContainersGenerated)   
    tviParent.ItemContainerGenerator.StatusChanged += new EventHandler(TempItemContainerGenerator_StatusChanged);   
    // If child items are already generated   
private void OnReadyToSelect()   
    // Here you can obtain and select any child of the currently selected TreeViewItem using it’s ItemContainerGenerator.    
    TreeViewItem childItem = tviParent.ItemContainerGenerator.ContainerFromItem(collectionItem); //Or specify an index.   
    childItem.IsSelected = true;   

Share with