通过创建多个小且封装良好的块,可以提高程序的可维护和可扩展性。在Flex中,通过自定义组件可以遵循这一标准流程。
自定义组件的方式之一是使用mxml文件。在一个自定义组件的mxml文档中,更标签必须是Application以外的其他Flex组件。
在下边的例子中,抽取包含Image和Label控件的条目渲染器和包含NumericStepper控件的条目编辑器到mxml文档中,作为自定义组件。
使用条目渲染器的方法是指定它的文件名作为itemRenderer属性的值。类似地,指定条目编辑器的文件名作为itemEditor属性的值。
提示:使用可重用的内联条目编辑器的时候,使用数据绑定把控件绑定到条目渲染器上。当你使用一个组件作为条目编辑器的时候,就不必使用数据绑定了。而是使用自定义组件的名字作为条目编辑器。
例子
NumericStepEditor component
<?xml version="1.0" encoding="utf-8"?>
<mx:VBox
xmlns:mx="http://www.adobe.com/2006/mxml"
horizontalAlign="center" verticalAlign="middle"
>
<mx:Script>
<!--[CDATA[
// Expose the editor's value
public function get newQuantity ():uint
{
return myStepper.value;
}
]]-->
</mx:Script>
<mx:NumericStepper
id="myStepper"
maximum="100"
stepSize="1"
value="{data.quantity}"
/>
</mx:VBox>
ImageRenderer component
<?xml version="1.0" encoding="utf-8"?>
<mx:VBox
xmlns:mx="http://www.adobe.com/2006/mxml"
horizontalAlign="center" verticalAlign="middle"
width="100%" height="140"
>
<mx:Image source="{'assets/'+data.image}"/>
<mx:Label text="{data.image}"/>
</mx:VBox>
Main application file
<?xml version="1.0" encoding="utf-8"?>
<mx:Application
xmlns:mx="http://www.adobe.com/2006/mxml"
viewSourceURL="src/ItemEditorComponent/index.html"
width="525" height="525"
>
<mx:Model id="artwork" source="model/artwork.xml"/>
<mx:DataGrid
rowCount="3" variableRowHeight="true"
dataProvider="{artwork.piece}"
editable="true"
>
<mx:columns>
<!-- Use the ImageRenderer custom component as an item renderer -->
<mx:DataGridColumn
dataField="image" headerText="Image" width="150"
itemRenderer="ImageRenderer"
/>
<mx:DataGridColumn headerText="Name" dataField="name"/>
<mx:DataGridColumn headerText="Price" dataField="price"/>
<!--
Use the NumericStepRenderer custom component
as an item renderer.
-->
<mx:DataGridColumn
headerText="Quantity"
dataField="quantity"
itemEditor="NumericStepEditor"
editorDataField="newQuantity"
>
</mx:DataGridColumn>
</mx:columns>
</mx:DataGrid>
<mx:LinkButton
textAlign="center"
label="Photos (c) 2006 geishaboy500 (CC Attribution License)"
click="{navigateToURL(new URLRequest('http://www.flickr.com/photos/geishaboy500/'));}"
/>
<mx:Script>
<!--[CDATA[
import flash.net.navigateToURL;
]]-->
</mx:Script>
</mx:Application>