在绑定中使用数组------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,这会触发对数组元素的所有数据绑定而不论它们是如
何实现的。

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