WPF TreeView 展開和閉合所有節點
阿新 • • 發佈:2019-02-05
tvProperties為TreeView的名稱。
Private Sub ExpandAll_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
For Each item As Object In tvProperties.ItemsDim treeItem As TreeViewItem = TryCast(tvProperties.ItemContainerGenerator.ContainerFromItem(item), TreeViewItem)
If treeItem IsNot Nothing Then
ExpandAll(treeItem, True)
End If
treeItem.IsExpanded = True
Next
End Sub
Private Sub ExpandAll(item As ItemsControl, expand As Boolean)
For Each obj As Object In item.Items
'如果TreeViewItem未被展開過,則無法通過ItemContainerGenerator來查詢這個TreeViewItem下的子節點。
‘所以需要先將TreeViewItem的IsExpanded屬性設定為True,並呼叫UpdateLayout方法。
’即需要先展開該節點才能獲取到該節點下的子節點。也就是需要從根節點開始展開直到最末端的節點。收回時相反。
If expand And obj IsNot Nothing And Not obj.IsExpanded Then
Dim tviCurrent As TreeViewItem = TryCast(item, TreeViewItem)tviCurrent.SetValue(TreeViewItem.IsExpandedProperty, True)
tviCurrent.UpdateLayout()
End If
Dim childControl As ItemsControl = TryCast(item.ItemContainerGenerator.ContainerFromItem(obj), ItemsControl)
If childControl IsNot Nothing Then
ExpandAll(childControl, expand)
End If
‘閉合時則從最末端的節點往根節點收回
If Not expand Then
Dim subItem As TreeViewItem = DirectCast(childControl, TreeViewItem)
subItem.IsExpanded=expand
End If
Next
End Sub
Private Sub CollapseAll_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
For Each item As Object In tvProperties.Items
Dim treeItem As TreeViewItem = TryCast(tvProperties.ItemContainerGenerator.ContainerFromItem(item), TreeViewItem)
If treeItem IsNot Nothing Then
ExpandAll(treeItem, False)
End If
treeItem.IsExpanded = False
Next
End Sub