How to programmatically select an item in a WPF TreeView?

后端 未结 16 2340
时光取名叫无心
时光取名叫无心 2020-11-28 08:42

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

16条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-28 09:06

    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.

提交回复
热议问题