在綁定中使用數組------ArrayCollection

                            在綁定中使用數組
在使用數組進行工作時,比如Array 或者ArrayCollection 對象,可以把數組作爲數據綁定
表達式的源或目的。


注意: 當使用數組作爲綁定源時,應該使用ArrayCollection 類型的數組,因爲ArrayCollection 類在數組或數組元素髮生變化時能夠發出事件來觸發數據綁定。

比如,對ArrayCollection.addItem(), ArrayCollection.addItemAt(),ArrayCollection.removeItem(), 以及ArrayCollection.removeItemAt()方法的調用都會觸發數據綁定。

綁定到數組通常將數組綁定給Flex 控件的dataProvider 屬性,

 

 

下面範例說明將數組綁定用於List 控件:
<?xml version="1.0"?>
<!-- binding/ArrayBindingDP.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
[Bindable]
public var myAC:ArrayCollection = new ArrayCollection(["One", "Two", "Three", "Four"]);
[Bindable]
public var myAC2:ArrayCollection = new ArrayCollection(["Uno", "Dos", "Tres", "Quatro"]);
]]>
</mx:Script>
<!-- Data binding updated at application startup,
when myAC is modified, and when an element of
myAC is modifed. -->


<mx:List dataProvider="{myAC}"/>
<!-- Data bindings to myAC updated. -->


<mx:Button label="Change Element" click="myAC[0]='mod One'"/>
<!-- Data bindings to myAC updated. -->


<mx:Button label="Add Element"  click="myAC.addItem('new element');"/>
<!-- Data bindings to myAC updated. -->


<mx:Button label="Remove Element 0" click="myAC.removeItemAt(0);"/>
<!-- Data bindings to myAC updated. -->


<mx:Button  label="Change ArrayCollection"  click="myAC=myAC2"/>
</mx:Application>


這個例子定義了一個ArrayCollection 對象,然後將List 控件的dataProvider 屬性設置爲對這個ArrayCollection 的數據綁定。當修改ArrayCollection 對象中的元素,

或者修改對ArrayCollection 對象的引用,都會觸發數據綁定。
綁定到數組中的元素
可以使用數組中的單個元素作爲數據綁定源,如下例所示:
<?xml version="1.0"?>
<!-- binding/ArrayBinding.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
[Bindable]
public var myAC:ArrayCollection = new ArrayCollection([
"One", "Two", "Three", "Four"]);
[Bindable]
public var myAC2:ArrayCollection = new ArrayCollection([
"Uno", "Dos", "Tres", "Quatro"]);
]]>
</mx:Script>
<!-- Data binding updated at application startup
and when myAC modified. -->
<mx:Text id="text1" text="{myAC[0]}"/>
<!-- Data binding updated at application startup,
when myAC modified, and when myAC[0] modified. -->
<mx:Text id="text2" text="{myAC.getItemAt(0)}"/>
<mx:Button id="button1"
label="Change Element"
click="myAC[0]='new One'"/>
<mx:Button id="button2"
label="Change ArrayCollection"
click="myAC=myAC2"/>
</mx:Application>
如果通過方括號語法[]來指定數組元素作爲數據綁定表達式的源,那麼數據綁定只在應用
啓動時觸發,或者在數組或其引用被更新時觸發。當這個數組元素被更新的時候不會觸發數據
綁定。
但數據綁定表達式中的myAC.getItemAt(0)則會在該數組元素變化時被觸發更新。因此,id
爲 text2 的Text 控件在點擊button1 時會被更新,而id 爲text1 的Text 控件則不會被更新。
當使用數組中的元素作爲數據綁定表示的源時,應當在綁定表達式中使用
ArrayCollection.getItemAt()方法。

點擊button2 時將myAC2 拷貝給myAC,這會觸發對數組元素的所有數據綁定而不論它們是如
何實現的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章