Expanding a treeview to a specific node in WPF

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);
            }
        }

comment from neil
I am trying to work on the same problem, trying to search for a text in the treeview nodes in WPF. I tried your example and my application is crashing. Did this one work in WPF? How did the treeview look like?

comment from Mohammad
Hi, I've tried it. It's not working !

comment from David Dikman
Hi The problem with this is that normally you wouldn't have a hierarchy of TreeViewItems but rather some other model which has lists/collections of subitems. Then you´d display this in the treeview using a hierarchial datatemplate in which case tv.Items would contain that model (and on top of that only the root nodes of that model). If you´ve got any way to retrieve the TreeViewItems in this case it would be greatly appreciated.

comment from in in
I did this a different way because I could not get the menu to open either. It seems that it is optimized to only open the top level. Even trying to force desired items opened didn't work. So instead, I set the TreeViewItem style to have IsExpanded as true, and then in the application, I close the ones I don't want shown in the Window1_Loaded routine (for the Loaded event). Not too efficent, but it gets the job done. <TreeView.ItemContainerStyle> <Style TargetType="{x:Type TreeViewItem}"> <Setter Property="IsExpanded" Value="True"> </Setter> </Style> </TreeView.ItemContainerStyle>

add a comment
name:
website:
email:
comment: