可以通过labelFunction来自定义ComboBox、tree等组件的显示内容。有时我们需要统计非叶子节点子节点的个数。利用labelFunction就可以很容易的实现该功能,当然也可以通过itemRenderer实现。
private function tree_labelFunc(item:XML):String {
var children:ICollectionView;
var suffix:String = "";
if (tree.dataDescriptor.isBranch(item)) {
children = tree.dataDescriptor.getChildren(item);
suffix = " (" + children.length + ")";
}
return item[tree.labelField] + suffix;
}
<mx:Tree id="tree"
dataProvider="{dp}"
showRoot="false"
labelField="@label"
labelFunction="tree_labelFunc"
width="300"
rowCount="6"
itemClick="tree_itemClick(event);" />
利用itemRenderer实现labelFunction的功能。
package myComponents
{
// itemRenderers/tree/myComponents/MyTreeItemRenderer.as
import mx.controls.treeClasses.*;
import mx.collections.*;
public class MyTreeItemRenderer extends TreeItemRenderer
{
// Define the constructor.
public function MyTreeItemRenderer() {
super();
}
// Override the set method for the data property
// to set the font color and style of each node.
override public function set data(value:Object):void {
super.data = value;
if(TreeListData(super.listData).hasChildren)
{
setStyle("color", 0xff0000);
setStyle("fontWeight", 'bold');
}
else
{
setStyle("color", 0x000000);
setStyle("fontWeight", 'normal');
}
}
// Override the updateDisplayList() method
// to set the text for each tree node.
override protected function updateDisplayList(unscaledWidth:Number,
unscaledHeight:Number):void {
super.updateDisplayList(unscaledWidth, unscaledHeight);
if(super.data)
{
if(TreeListData(super.listData).hasChildren)
{
var tmp:XMLList =
new XMLList(TreeListData(super.listData).item);
var myStr:int = tmp[0].children().length();
super.label.text = TreeListData(super.listData).label +
"(" + myStr + ")";
}
}
}
}
}
设置label字体颜色
<mx:Tree id="tree" x="3" y="3" width="100%" height="100%" borderVisible="false" color="#4A4949"
contentBackgroundColor="#D8D8D8" dataProvider="{treeXml}"
fontFamily="黑体" fontSize="13" iconField="@icon"
labelField="@label" selectedItem="{}" selectionColor="#3DDDDB" showRoot="false" indentation="10">
<mx:itemRenderer>
<fx:Component>
<mx:TreeItemRenderer>
<fx:Script>
<![CDATA[
override protected function updateDisplayList(
unscaledWidth:Number, unscaledHeight:Number):void{
super.updateDisplayList(unscaledWidth, unscaledHeight);
if (listData) {
var depth:int = listData['depth'];
switch (depth) {
case 1:
label.setColor(0x0f0f0f);
break;
case 2:
label.setColor(0x666666);
break;
}
}
}
]]>
</fx:Script>
</mx:TreeItemRenderer>
</fx:Component>
</mx:itemRenderer>
</mx:Tree>