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.
my code:
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?
Andy's solution will work for your needs, but a more versatile and reusable solution would be to iterate using
ItemCollection
. With this you can pass any object type that inherits anItemCollection
while avoiding exceptions for sub-items that don't. This a great if you have different types of children in your tree.I made two recursive methods. the first initially searched the
TreeView
for the desired item, then the second searched eachitem
until the desired item was found. the method then returned the desired item which I was able to manipulate like I wanted to.Code:
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:
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.