2013-12-10 44 views
1

我有一個WPF應用程序,其中我有一個樹視圖控件。CollapseWPF應用程序中的treeview的所有項目

我想通過單擊按鈕摺疊所有項目。我試過這個:

private void buttonParam_Click(object sender, RoutedEventArgs e) 
     { 
//handling 
    this.arborescence.IsExpanded = false; 
     } 

但它沒有奏效。這個錯誤的原因是什麼?我如何更改我的代碼片段來完成此任務?

回答

3

我認爲要做到這一點的最好辦法是通過所有節點循環和1

private void cmdCollapse_Click(object sender, RoutedEventArgs e) 
{ 
    foreach (TreeViewItem item in treeview.Items) 
     CollpaseTreeviewItems(item); 
} 

void CollapseTreeviewItems(TreeViewItem Item) 
{ 
    Item.IsExpanded = false; 

    foreach (TreeViewItem item in Item.Items) 
    { 
     item.IsExpanded = false; 

     if (item.HasItems) 
      CollapseTreeviewItems(item); 
    } 
} 
0

@JROs塌陷他們1 answer將無法​​正常工作時,數據綁定到項目,它只會在直接將TreeViewItem s加入TreeView

我提出此擴展方法,該方法將檢索匹配TreeViewItem用於在迭代的當前對象:

namespace System.Windows.Controls 
{ 
    using System.Linq; 
    public static class TreeViewExtensions 
    { 
    public static void SetExpansion(this TreeView treeView, bool isExpanded) => 
     SetExpansion((ItemsControl)treeView, isExpanded); 

    static void SetExpansion(ItemsControl parent, bool isExpanded) 
    { 
     if (parent is TreeViewItem tvi) 
     tvi.IsExpanded = isExpanded; 

     if (parent.HasItems) 
     foreach (var item in parent.Items.Cast<object>() 
     .Select(i => GetTreeViewItem(parent, i, isExpanded))) 
      SetExpansion(item, isExpanded); 
    } 

    static TreeViewItem GetTreeViewItem(
     ItemsControl parent, object item, bool isExpanded) 
    { 
     if (item is TreeViewItem tvi) 
     return tvi; 

     var result = ContainerFromItem(parent, item); 
     if (result == null && isExpanded) 
     { 
     parent.UpdateLayout(); 
     result = ContainerFromItem(parent, item); 
     } 
     return result; 
    } 

    static TreeViewItem ContainerFromItem(ItemsControl parent, object item) => 
     (TreeViewItem)parent.ItemContainerGenerator.ContainerFromItem(item); 
    } 
} 

用法:

treeView.SetExpansion(isExpanded: true/false); 
相關問題