1.首先看一个节省代码的一般写法
mxml组件:MyGruop.mxml
<?xml version="1.0" encoding="utf-8"?> <s:Group xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" width="250" height="108"> <fx:Script> <![CDATA[ //要加上public修饰外边文件方可使用到 [Bindable] public var fileName:String; [Bindable] public var age:String; ]]> </fx:Script> <mx:Form x="21" y="10" width="220" height="88"> <mx:FormItem label="姓名:"> <s:TextInput text="{fileName}" /> </mx:FormItem> <mx:FormItem label="年龄:"> <s:TextInput text="{age}"/> </mx:FormItem> </mx:Form> </s:Group>
主应用程序的main.mxml中只需调用这样的代码
<components:MyGroup fileName="梁静茹" age="88" />
<components:MyGroup fileName="周杰伦" age="31" />
2.由于上边调用时值直接写属性有点硬编码,所以想到用类似JAVA程序的对象来处理效果会更好
在Flex4中那么就会出现一个ActionScript类,以.as结尾的文件
MyActionScript.as
package components
{
public class MyActionScript
{
[Bindable]
public var fileName:String;
[Bindable]
public var age:String;
public function MyActionScript(fileName:String,age:String)
{
this.fileName=fileName;
this.age=age;
}
}
}
MyGroup.mxml中代码不变,main.mxml中这么使用
先在<fx:Script>中实例化对象
[Bindable]
private var mac:MyActionScript=new MyActionScript("蔡依林","30");
[Bindable]
private var mac1:MyActionScript=new MyActionScript("王力宏","31");
然后具体使用代码为
<mx:FormItem>
<components:MyGroup fileName="{mac.fileName}" age="{mac.age}" />
<components:MyGroup fileName="{mac1.fileName}" age="{mac1.age}" />
</mx:FormItem>
3、第二种方式似乎仍然不是太满意,能直接绑定一个对象或许会更好
这是我们的MyGroup.mxml中的代码要发生改变
<?xml version="1.0" encoding="utf-8"?>
<s:Group xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" width="250" height="108">
<fx:Script>
<![CDATA[
//要加上public修饰外边文件方可使用到
[Bindable]
public var mac:MyActionScript;
]]>
</fx:Script>
<mx:Form x="81" y="63" width="220" height="88">
<mx:FormItem label="姓名:">
<s:TextInput text="{mac.fileName}" />
</mx:FormItem>
<mx:FormItem label="年龄:">
<s:TextInput text="{mac.age}"/>
</mx:FormItem>
</mx:Form>
</s:Group>
这次MyActionScript.as不变,main.mxml中具体使用如下
先在<fx:Script>中实例化对象
[Bindable]
private var mac:MyActionScript=new MyActionScript("蔡依林","30");
[Bindable]
private var mac1:MyActionScript=new MyActionScript("王力宏","31");
然后具体使用代码为
<mx:FormItem>
<components:MyGroup mac="{mac}"/>
<components:MyGroup mac="{mac1}"/>
</mx:FormItem>