在运行时添加一个空的枝节点
可以在运行时向Tree控件添加空的枝节点。下边的例子展示了通过数据提供器(data provider)API和数据描述器(data descriptor )API添加枝节点。通常,添加枝节点的首选途径是通过数据提供器(data provider)API。
addEmptyBranthDP()方法通过数据提供器API向使用XML数据提供器的Tree组件增加一个空节点,这个方法为新节点创建一个XML类型的变量,并且设置这个节点的isBranch属性为true来创建一个枝节点。然后这个方法调用Tree控件的dataProvider.addItemAt()方法来向Tree控件的数据提供器增加新的元素。
addEmptyBranchDP2()方法通过数据提供器API向使用对象数据提供器的Tree组件增加一个空节点,这个方法使用children属性创建一个新的对象,使用children属性能够确保isBranch()方法返回true。然后,这个方法调用Tree控件的dataProvider.addItemAt()方法来向Tree控件的数据提供器增加新的对象。
addEmptyBranchDD()方法通过数据描述器(data descripter)API。这个方法创建一个XML类型的变量,并且设置isBranch属性为true来创建一个枝节点。然后,这个方法调用Tree控件的dataDescriptor.addChildAt()方法来向Tree控件的数据描述器添加一个新的子节点。
例子
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" viewSourceURL="src/index.html"> <mx:Script>
<![CDATA[
[Bindable]
private var dataX:XML =
<item label="Top">
<item label="Child One"/>
<item label="Child Two" />
</item>;
[Bindable]
private var dataObj:Object =
[{label:"Top", children:
[
{label:"Child One"}, {label: "Child Two"}
]
}];
// Adding a branch by going through the Tree control's dataProvider. This is
// the preferred method.
// Toggling the isBranch attribute to true causes DefaultDataDescriptor.isBranch()
// to return true and the Tree treats the node as a branch.
private function addEmptyBranchDP():void
{
var newNode:XML = <item label='Middle' isBranch="true"></item>;
xmlBound2Tree.dataProvider.addItemAt(newNode, 1);
}
// For an object graph, the key point is that the children property needs to be defined,
// even if it is empty.
// This causes isBranch() to return true and the Tree treats the new node as a branch.
private function addEmptyBranchDP2():void
{
var newObj:Object = {label:"Middle", children:[]};
objGraphBound2Tree.dataProvider.addItemAt(newObj, 1);
}
// Adding a branch by going through the Tree control's dataDescriptor.
private function addEmptyBranchDD():void
{
var newNode:XML = <item label='Child 4' isBranch="true"></item>;
xmlBound2Tree.dataDescriptor.addChildAt(dataX, newNode, 2, dataX);
}
]]>
</mx:Script>
<mx:Label text="Tree with XML data"/>
<mx:Tree id="xmlBound2Tree" dataProvider="{dataX}" labelField="@label" showRoot="true" width="200"/>
<mx:Button label="Add Empty Branch through the dataProvider" click="addEmptyBranchDP();"/>
<mx:Button label="Add Empty Branch through the dataDescriptor" click="addEmptyBranchDD();"/>
<mx:Spacer height="10"/>
<mx:Label text="Tree with object data"/>
<mx:Tree id="objGraphBound2Tree" dataProvider="{dataObj}" width="200"/>
<mx:Button label="Add Empty Branch through the dataProvider" click="addEmptyBranchDP2();"/>
</mx:Application>