The following code shows you how you can use an Array as a data provider for a Tree control in Flex.
Full code after the jump.
<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2007/12/03/using-an-array-as-a-data-provider-in-a-flex-tree-control/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical"
verticalAlign="middle"
backgroundColor="white">
<mx:Script>
<![CDATA[
private function tree_labelFunc(item:Object):String {
var suffix:String = "";
if (tree.dataDescriptor.hasChildren(item)) {
suffix = " (" + item.children.length + ")";
}
return item.name.toUpperCase() + suffix;
}
]]>
</mx:Script>
<mx:Array id="arr">
<mx:Object name="One">
<mx:children>
<mx:Array>
<mx:Object name="Two" />
<mx:Object name="Three" />
<mx:Object name="Four">
<mx:children>
<mx:Array>
<mx:Object name="Five" />
<mx:Object name="Six" />
</mx:Array>
</mx:children>
</mx:Object>
<mx:Object name="Seven">
<mx:children>
<mx:Array>
<mx:Object name="Eight" />
</mx:Array>
</mx:children>
</mx:Object>
<mx:Object name="Nine" />
</mx:Array>
</mx:children>
</mx:Object>
</mx:Array>
<mx:Tree id="tree"
dataProvider="{arr}"
labelFunction="tree_labelFunc"
width="200" />
</mx:Application>
View source is enabled in the following example.
And if you happen to be using Flex 4 (download), the following example should work:
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/halo">
<fx:Script>
<![CDATA[
private function tree_labelFunc(item:Object):String {
var suffix:String = "";
if (tree.dataDescriptor.hasChildren(item)) {
suffix = " (" + item.children.length + ")";
}
return item.name.toUpperCase() + suffix;
}
]]>
</fx:Script>
<fx:Declarations>
<fx:Array id="arr">
<fx:Object name="One">
<fx:children>
<fx:Array>
<fx:Object name="Two" />
<fx:Object name="Three" />
<fx:Object name="Four">
<fx:children>
<fx:Array>
<fx:Object name="Five" />
<fx:Object name="Six" />
</fx:Array>
</fx:children>
</fx:Object>
<fx:Object name="Seven">
<fx:children>
<fx:Array>
<fx:Object name="Eight" />
</fx:Array>
</fx:children>
</fx:Object>
<fx:Object name="Nine" />
</fx:Array>
</fx:children>
</fx:Object>
</fx:Array>
</fx:Declarations>
<mx:Tree id="tree"
dataProvider="{arr}"
labelFunction="tree_labelFunc"
width="200"
horizontalCenter="0"
verticalCenter="0" />
</s:Application>

{ 2 comments… read them below or add one }
Nice one.
Do you know how I can navigatie in a viewstack with a tree?
public function treeChanged(event:Event):void { if(event.target.selectedItem.@vs == "") { Alert.show("empty"); } else { contentA.selectedChild = Tree(event.target).selectedItem.@vs as Container; }But that doesn’t work.
Just hardcoded stuff….. its nothing special