Open all branches in a Flex tree
I need to create a Tree in Flex which starts off with all the nodes opened. This proves to be much harder than you might think. The solution I have found relies on a bit of hacking to keep track of when the Tree's data provider has been loaded, and then “flattening” the tree data structure into an ArrayCollection and using that as the openItems property of the Tree. In my case I am using an ArrayCollection of Objects as the data source.
A bonus is the ability to open the Tree to a particular depth. This comes in handy to stop a very deep tree from running away with your scripting.
<mx:Application xmlns:mx=“http://www.adobe.com/2006/mxml“> <mx:Script> <![CDATA[ import flash.events.*; import mx.collections.ArrayCollection; import mx.controls.*; import mx.core.*; public var categoryTreeOpened:Boolean = false; public var categories:ArrayCollection; // create categories tree data structure as nested ArrayCollections of objects here // label function for components which read from objects protected function objectLabel(item:Object):String { return item.name; } // open the category tree first time it is rendered public function openAllCategories(event:Event = null):void { if ((categoryTreeOpened == false) && (this.categories != null)) { var openItems:ArrayCollection = this.flattenCategoryTree(this.categories, new ArrayCollection(), 4); this.trCategories.openItems = openItems; categoryTreeOpened = true; } } // flatten the category tree to a certain level protected function flattenCategoryTree(_categories:ArrayCollection, input:ArrayCollection, level:Number = 5):ArrayCollection { if (level == 0) return new ArrayCollection(); for each (var _category:Object in _categories) { input.addItem(_category); input = new ArrayCollection(input.toArray().concat(flattenCategoryTree(_category.children, input, level-1).toArray())); } return input; } ]]> </mx:Script> <mx:Tree dataProvider=“{categories}“ labelFunction=“objectLabel“ id=“trCategories“ render=“openAllCategories()“/> </mx:Application>
