Flex中的数据绑定(Data Binding)2:例子
在上一篇讨论了flex中数据绑定的原理,这里看一下实际的例子,代码如下:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="init()">
<mx:Script>
<![CDATA[
import mx.events.PropertyChangeEvent;
import test.BindableClass;
[Bindable]
private var intValue:int = 100;
private var bc:BindableClass = new BindableClass();
private function init():void{
this.addEventListener(PropertyChangeEvent.PROPERTY_CHANGE,onChange);
bc.addEventListener(PropertyChangeEvent.PROPERTY_CHANGE,onChange);
}
private function onChange(event:PropertyChangeEvent){
msgText.text = msgText.text+"src="+
event.source+" target="+
event.target+" curentTarget="+
event.currentTarget+" newValue="+
event.newValue+" ";
}
]]>
</mx:Script>
<mx:Button id="btn1" width="{intValue}" label="{bc.str+String(intValue)}"/>
<mx:Button x="200" width="{300-btn1.width}"/>
<mx:Button y="30" label="Button" click="intValue+=1;"/>
<mx:Button x="100" y="30" label="Button" click="bc.str+='a';"/>
<mx:TextArea id="msgText" y="60" height="300" width="550"/>
</mx:Application>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="init()">
<mx:Script>
<![CDATA[
import mx.events.PropertyChangeEvent;
import test.BindableClass;
[Bindable]
private var intValue:int = 100;
private var bc:BindableClass = new BindableClass();
private function init():void{
this.addEventListener(PropertyChangeEvent.PROPERTY_CHANGE,onChange);
bc.addEventListener(PropertyChangeEvent.PROPERTY_CHANGE,onChange);
}
private function onChange(event:PropertyChangeEvent){
msgText.text = msgText.text+"src="+
event.source+" target="+
event.target+" curentTarget="+
event.currentTarget+" newValue="+
event.newValue+" ";
}
]]>
</mx:Script>
<mx:Button id="btn1" width="{intValue}" label="{bc.str+String(intValue)}"/>
<mx:Button x="200" width="{300-btn1.width}"/>
<mx:Button y="30" label="Button" click="intValue+=1;"/>
<mx:Button x="100" y="30" label="Button" click="bc.str+='a';"/>
<mx:TextArea id="msgText" y="60" height="300" width="550"/>
</mx:Application>
test.BindableClass如下:
package test
{
[Bindable]
public class BindableClass
{
public var str:String = "width=";
}
}
{
[Bindable]
public class BindableClass
{
public var str:String = "width=";
}
}
flex中的数据绑定主要通过mxml中标签的属性定义实现,将属性值设置为用大括号“{}”标识的数据源,则该数据源指向的数据就被绑定到组件的属性上。
在上面的例子中,使用了几种数据源:
1. mxml的Script中定义的变量(该变量已声明[Bindable]标记):width="{intValue}"
2. ActionScript类中定义的变量(该类已经声明[Bindable]标记):label="{bc.str+String(intValue)}"
3. mxml中其他组件的属性:width="{300-btn1.width}"
4. 可以将运算的结果作为数据源.