Expanding a treeview to a specific node in WPF

Originally published on eve.gd on 30 July 2008.

Read this post on the web (with images, PDF and citation details)

I've been exploring the dark alleyways of the Windows Presentation Foundation this week and found no way in my trawlings of the net to expand a treeview to a specific node.

No FindNode, no ExpandTo or ExpandAll. Great.

Anyway, here's the solution I came up with. It relies upon a binding the Tag property to the text you are searching for, but that could obviously be changed.

        /// <summary>
        /// Expand a TreeView to a specific node
        /// </summary>
        /// <param name="tv">The treeview</param>
        /// <param name="node">The string of the node in the Item.Tag property to expand to</param>
        void jumpToFolder(TreeView tv, string node)
        {
            bool done = false;
            ItemCollection ic = tv.Items;

            while (!done)
            {
                bool found = false;

                foreach (TreeViewItem tvi in ic)
                {    
                    if (node.StartsWith(tvi.Tag.ToString()))
                    {
                        found = true;
                        tvi.IsExpanded = true;
                        ic = tvi.Items;
                        if (node == tvi.Tag.ToString()) done = true;
                        break;
                    }
                }

                done = (found == false && done == false);
            }
        }