Search code examples
c#.netwpftreeviewitemscontrol

How to programmatically select an item in a WPF TreeView?


How is it possible to programmatically select an item in a WPF TreeView? The ItemsControl model seems to prevent it.


Solution

  • It's a real pain for some strange reason, you have to use ContainerFromItem to get the container, then invoke the select method.

    //  selectedItemObject is not a TreeViewItem, but an item from the collection that 
    //  populated the TreeView.
    
    var tvi = treeView.ItemContainerGenerator.ContainerFromItem(selectedItemObject) 
              as TreeViewItem;
    
    if (tvi != null)
    {
        tvi.IsSelected = true;
    }
    

    There once was a blog entry on how to do it here, but the link is dead now.