How to programmatically select an item in a WPF TreeView?

后端 未结 16 2325
时光取名叫无心
时光取名叫无心 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:03

    This is my solution. The others failed for me in various ways. You need to walk the tree from top to bottom, looking for the tree item at each level, expanding and updating the layout along the way.

    This function takes a stack of nodes where the first one out of the stack is the top most node, and each subsequent node on the stack is a child of the previous parent. The second argument is the TreeView.

    As each item is found, that item is expanded, and the final item is returned, where the caller can select it.

        TreeViewItem FindTreeViewItem( Stack nodeStack, TreeView treeView )
        {
            ItemsControl itemsControl = treeView;
    
            while (nodeStack.Count > 0) {
                object node = nodeStack.Pop();
                bool found = false;
    
                foreach (object item in itemsControl.Items) {
                    if (item == node) {
                        found = true;
    
                        if (itemsControl.ItemContainerGenerator.ContainerFromItem( item ) is TreeViewItem treeViewItem) {
                            if (nodeStack.Count == 0) {
                                return treeViewItem;
                            }
    
                            itemsControl = treeViewItem;
                            treeViewItem.IsExpanded = true;
                            treeViewItem.UpdateLayout();
                            break;
                        }
                    }
                }
    
                if (!found) {
                    return null;
                }
            }
    
            return null;
        }
    
    
    

    Example of how to call it:

        // Build nodeStack here from your data
    
        TreeViewItem treeViewItem = FindTreeViewItem( nodeStack, treeView );
    
        if (treeViewItem != null) {
            treeViewItem.IsSelected = true;
            treeViewItem.BringIntoView();
        }
    

    提交回复
    热议问题