Get all TreeViewItems from TreeView in Silverlight 4

Let’s suppose TreeView control is filled with TreeViewItems in xaml and we need a collection of all the TreeViewItems in code file then it’s becomes a tricky task.

Actually we have to implement a recursive method that  will iterate over the collection of TreeViewItem and will search depth first.

Hope below code will make it clear to understand. If anything is unclear feel free to ask.

Sample XAML goes like this :

<Grid x:Name="LayoutRoot" Background="White">
<toolkit:TreeView x:Name="MyTreeView">
<toolkit:TreeViewItem Header="Announcements"/>
<toolkit:TreeViewItem Header="Products">
<toolkit:TreeViewItem Header="Controls"/>
<toolkit:TreeViewItem Header="Media Players"/>
<toolkit:TreeViewItem Header="Games"/>
<toolkit:TreeViewItem Header="Charts"/>
<toolkit:TreeViewItem Header="Tools"/>
<toolkit:TreeViewItem Header="Moonlight"/>
<toolkit:TreeViewItem Header="Demos"/>
<toolkit:TreeViewItem Header="Learn">
<toolkit:TreeViewItem Header="Videos"/>
<toolkit:TreeViewItem Header="Presentations"/>
<toolkit:TreeViewItem Header="Tutorials"/>
<toolkit:TreeViewItem Header="Resources"/>
<toolkit:TreeViewItem Header="Samples"/>
<toolkit:TreeViewItem Header="QuickStarts"/>
<toolkit:TreeViewItem Header="Tips and Tricks"/>
<toolkit:TreeViewItem Header="Issues"/>
<toolkit:TreeViewItem Header="Misc"/>
<toolkit:TreeViewItem Header="Write and Win Contest"/>


And Code File goes like this :

public partial class TreeViewTest : UserControl
List allItems = new List();

public TreeViewTest()
List allTreeContainers = GetAllItemContainers(MyTreeView);

private List GetAllItemContainers(System.Windows.Controls.ItemsControl itemsControl)

for (int i = 0; i < itemsControl.Items.Count; i++)
if ((itemsControl.Items[i] as TreeViewItem).HasItems)
allItems.Add(itemsControl.Items[i] as TreeViewItem);
GetAllItemContainers(itemsControl.Items[i] as TreeViewItem);
allItems.Add(itemsControl.Items[i] as TreeViewItem);
return allItems;


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s