<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="horizontal">
<mx:Script>
<![CDATA[
[Bindable]
public var dataAry:Array =
[{label: "Item 01"},{label: "Item 02"},{label: "Item 03"},{label: "Item 04"}];
public function selectAll():void{
list1.selectedItems = dataAry;
trace(list1.selectedIndices);
}
]]>
</mx:Script>
<mx:List id="list1" width="100" height="100%" dataProvider="{dataAry}" />
<mx:Button label="Select All" click="selectAll();"/>
</mx:Application>
<!-- Ticore's Blog - http://ticore.blogspot.com/ -->
實際測試就會發現,非但無法做全選
List 資料還會發生錯亂
點一下,List Items 就消失一半
另一種陷阱是利用 ListBase.selectedIndices 作選擇
以下程式產生 Indices 陣列,同時指定給多個相同資料來源的 List 做全選功能
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="horizontal">
<mx:Script>
<![CDATA[
[Bindable]
public var dataAry:Array =
[{label: "Item 01"},{label: "Item 02"},{label: "Item 03"},{label: "Item 04"}];
public function selectAll():void{
var indices:Array = [];
for (var i:Number = 0 ; i < dataAry.length ; ++i) {
indices.push(i);
}
list1.selectedIndices = indices;
list2.selectedIndices = indices;
list3.selectedIndices = indices;
}
]]>
</mx:Script>
<mx:List id="list1" width="100" height="100%" dataProvider="{dataAry}" />
<mx:List id="list2" width="100" height="100%" dataProvider="{dataAry}" />
<mx:List id="list3" width="100" height="100%" dataProvider="{dataAry}" />
<mx:Button label="Select All" click="selectAll();"/>
</mx:Application>
實際測試就會發現,只有第一個 List 可以正確作選擇
如下圖所示:
由於指定陣列資料給 ListBase.selectedItems, selectedIndices 時
ListBase 本身並不會另外複製一份陣列
造成程式多處同時修改或是排序陣列資料
List 組件錯亂
所以正確的做法應該是每次都要產生新的陣列指定給 selectedItems, selectedIndices
嫌麻煩的話,也可以從已經指定好資料的 List 組件取得 selectedItems, selectedIndices
再指定給下一個 List
因為 get selectedItems, selectedIndices 是會得到一份 clone
正確的 selectedIndices 使用方式:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="horizontal">
<mx:Script>
<![CDATA[
[Bindable]
public var dataAry:Array =
[{label: "Item 01"},{label: "Item 02"},{label: "Item 03"},{label: "Item 04"}];
public function selectAll():void{
var indices:Array = [];
for (var i:Number = 0 ; i < dataAry.length ; ++i) {
indices.push(i);
}
list1.selectedIndices = indices;
list2.selectedIndices = list1.selectedIndices;
list3.selectedIndices = list2.selectedIndices;
}
]]>
</mx:Script>
<mx:List id="list1" width="100" height="100%" dataProvider="{dataAry}" />
<mx:List id="list2" width="100" height="100%" dataProvider="{dataAry}" />
<mx:List id="list3" width="100" height="100%" dataProvider="{dataAry}" />
<mx:Button label="Select All" click="selectAll();"/>
</mx:Application>
<!-- Ticore's Blog - http://ticore.blogspot.com/ -->
相關連結:
Flex ListBase selectedIndices, selectedItems Bug