The C1TreeView for Silverlight component is a tool for displaying data in a hierarchical/tree format for a better visual experience. In this article I'm going to talk about expanding or collapsing all nodes at once rather than having to expand or collapse each node individually. Let's get started!
I'm sure most of you know the basics of binding C1TreeView to an ItemsSource. For those who are not familiar with binding C1TreeView, I'm going to share it in brief. You can download the sample at the bottom for details. C1TreeView can be bound to a hierarchical datasource using C1HierarchicalDataTemplate. We're going to use a List for the purpose of this article. You can use other sources as well, for eg. an ObservableCollection. We can load data in C1TreeView in the following way :
c1TreeView1.ItemsSource = Data.LoadData();
You may go through the following blog article for more details: http://our.componentone.com/2014/02/10/using-checkbox-in-componentone-treeview-control/
To expand or collapse a node you can simply set C1TreeViewItem's IsExpanded property to true/false. Sounds pretty straight forward, right! It isn't. Since C1TreeView is bound, you cannot directly access C1TreeViewItems and set the IsExpanded property. If you access the Items property of C1TreeView, it'll give you a list of the underlying data items. So, what do we do? Well, we need to find the visual C1TreeViewItems and then we can set their IsExpanded property. We need to loop recursively through the VisualTree of C1TreeView and fetch the child items using the VTreeHelper class.
public void ExpandAll()
{
if (itemList == null || itemList.Count == 0)
{
itemList = new List<C1TreeViewItem>();
IList<DependencyObject> items = new List<DependencyObject>();
VTreeHelper.GetChildrenOfType(c1TreeView1, typeof(C1TreeViewItem), ref items);
foreach (C1TreeViewItem item in items)
{
ExpandNodes(item);
}
}
else
{
foreach (C1TreeViewItem item in itemList)
{
item.IsExpanded = true;
}
}
}
public void ExpandNodes(C1TreeViewItem item)
{
item.IsExpanded = true;
itemList.Add(item);
Dispatcher.BeginInvoke(() =>
{
IList<DependencyObject> items = new List<DependencyObject>();
VTreeHelper.GetChildrenOfType(item, typeof(C1TreeViewItem), ref items);
foreach (C1TreeViewItem childItem in items)
{
ExpandNodes(childItem);
}
});
}
And we're done! Here's a video of the output :
This is a simple implementation showing how to expand/collapse all nodes at once on a button click. If you're loading data through a Web/WCF service, you can call the ExpandAll method in the Completed event of the service. You can download the sample for complete implementation from the link below. Download Sample