I am working with a wpf TreeView
. I am trying to search through all of the items in the TreeView
to find the desired TreeViewItem
within it.
parent
is a string
of the header of the desired item I am searching for.
foreach (TreeViewItem item in treeView.Items)
{
if (item.Header.ToString().Contains(parent))
{
//Do Something to item that is found
}
}
The problem that I am having with this code is that it will search through the top two layers of the TreeView
. If there is a item
within a item
within the TreeView
, then the item
is not found. With that being said I added to my code but it only prolonged the issue another level into the TreeView
.
foreach (TreeViewItem item in treeView.Items)
{
foreach(TreeViewItem subItem in item.Items)
{
if (subItem.Header.ToString().Contains(parent))
{
//Do Something to item that is found
}
}
if (item.Header.ToString().Contains(parent))
{
//Do Something to item that is found
}
}
Is there a way to search through the entire TreeView
along with all the items
within it? Could I possible search the TreeView
recursively?
You should look into recursion. Essentially, you want a method that takes a treeviewitem and iterates through all it's children. For each of those the method calls itself, passing in the child. If you've never done this before it's a bit mind melting when you first look at it. Get an understanding of the principle. But roughly:
private void recurseItem(TreeViewItem item)
{
foreach (var subItem in item.Items)
{
// compare header and return that item if you find it
if(!gotTheItem)
recurseItem(subItem);
}
}
You need a foreach loop through the tree's top level items passing each into it. Don't just paste this in (you just learn cut and paste then) read up on recursion and think about it. Note that you will want to signal you found the item by setting a bool flag once you got it and avoid iterating all the rest.
Note that this code is largely intended to introduce a newbie to the idea of recursion. It is not intended to be an ideal cut and paste solution.
If you try this with a bound treeview then you will find that the Items collection has the objects you bound rather than treeviewitems.