在Flex中让Tree绑定数据后自动展开树节点
用Flex/Flash做开发的同志们应该会使用 expandChildrenOf(item,true)方法来使用Tree组件在绑定数据后自动展开所有树型节点(不需要用户再自己点击展开节点,会方 便许多),而在Flex开发帮忙文档中很明确写道:
"If you set dataProvider and then immediately call expandChildrenOf() you may not see the correct behavior. You should either wait for the component to validate or call the validateNow() method. "
如果使用不当,是看不到任何效果的,这会让许多新手郁闷不以!
我发现网上流传下面两种代码:
第一种:
treePlayList.dataProvider=results;//刷新
treePlayList.validateNow();//全部展开
treePlayList.selectedIndex=0;
treePlayList.expandChildrenOf(treePlayList.selectedItem,true);
但有些人试过不行, 我也不知道为什么。
第二种:
某些稍微聪明一点的人受到 启发想用个延时后再执行就行了:
setTimeout(IniExpand, 1000); //延时1秒
private function IniExpand():void {
TreeView1.selectedIndex=1;
TreeView1.expandItem(TreeView1.selectedItem,true);
}
不过,我亲自试了,根本无 效嘛~
其实,我自己想到了一个我 认为是权威准确的方法,那就是用callLater方法,再加上匿名代理方法!!!
代码如 下:
myTree.callLater(
function ():void{myTree.expandChildrenOf(selectedItem.root[0],true);}
); //selectedItem.root当然起始节点了(这是在 flash builder 4中测试成功)
这个方法是在某天开窍突然 想到Flex/Flash会像C#语言那样,能在方法的参数体里定义一个匿名方法呢?, 类似C#里的匿名代理方法delegate, 结果一试果然成功了,呵呵.
转自:http://www.techmango.com/blog/article/FlexTech/Flex_Tree_Auto_expandChildrenOf.htm