Reputation: 4969
I'm trying to iterate through my Treeview, expanding all nodes however it runs into an InvalidCastException when ran;
Unable to cast object of type 'System.Data.DataRowView' to type 'System.Windows.Controls.TreeViewItem'.
My Code;
foreach (TreeViewItem treeitem in thetreeView.Items)
{
treeitem.IsExpanded = true;
}
Any ideas? I want to fire this from a button.
Upvotes: 3
Views: 10744
Reputation: 21863
just add this style
<TreeView.ItemContainerStyle>
<Style TargetType="TreeViewItem">
<Setter Property="IsExpanded" Value="True" />
</Style>
</TreeView.ItemContainerStyle>
for code please go through this link may be this can help u
http://bea.stollnitz.com/blog/?p=55
Upvotes: 14
Reputation: 4800
I've found an "Hackish" solution for that. It does not involved with inheritance like the solution suggested here (by Kishore Kumar)
I've added two buttons - "Collapse all" and "Expand All".
Code Behind:
private void btnCollapseAll_Click(object sender, RoutedEventArgs e)
{
foreach (var item in treeView.Items)
{
DependencyObject dObject = treeView.ItemContainerGenerator.ContainerFromItem(item);
CollapseTreeviewItems(((TreeViewItem)dObject));
}
}
private void btnExpandAll_Click(object sender, RoutedEventArgs e)
{
foreach (var item in treeView.Items)
{
DependencyObject dObject = treeView.ItemContainerGenerator.ContainerFromItem(item);
((TreeViewItem)dObject).ExpandSubtree();
}
}
private void CollapseTreeviewItems(TreeViewItem Item)
{
Item.IsExpanded = false;
foreach (var item in Item.Items)
{
DependencyObject dObject = treeView.ItemContainerGenerator.ContainerFromItem(item);
if (dObject != null)
{
((TreeViewItem)dObject).IsExpanded = false;
if (((TreeViewItem)dObject).HasItems)
{
CollapseTreeviewItems(((TreeViewItem)dObject));
}
}
}
}
My solution is based on this
Upvotes: 4
Reputation: 29584
Bag of tricks has a demo called "TreeView Expand" that has a tree view with expand all and collapse all buttons (and some more)
Upvotes: 0