Flex1 到 Flex3 使用的都是 Halo组件,这里将介绍Halo 组件中的List 和 DataGrid 。其中 DataGrid 是显示多列数据中最常用的方式。但是在Spark中还有没对应DataGrid的组件。
先写个“食物”的模型 Dinner.as 。
package model { [Bindable] public class Dinner { public var name:String; public var food:String; public var due:Date; public function Dinner( name:String = "", food:String = "", due:Date = null) { this.name = name; this.food = food; this.due = due == null ? new Date() : due; } } }
然后在对食物进行处理,相关解释以注释写在Mxml中。
<?xml version="1.0" encoding="utf-8"?> <s:Application 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="100%" height="100%"> <fx:Script> <![CDATA[ import mx.collections.ArrayCollection; import model.Dinner; [Bindable] private var _dinners:ArrayCollection = new ArrayCollection([ //创建一个“食物”集合 new Dinner("Breakfast", "Subway"), new Dinner("Lunch", "French"), new Dinner("Supper", "Japanese food"), new Dinner("Coffee"), new Dinner("Tea"), new Dinner("Wine")]); private function formatDinner(dinner:Dinner):String { //创建格式化数据的函数 return dinner.name + (dinner.food == "" ? "" : (" (" + dinner.food + ")")) + ", due on " + dateFormatter.format(dinner.due) + "."; } private function formatDate(item:Object, column:DataGridColumn):String { var dinner:Dinner = item as Dinner; return dinner == null ? "" : dateFormatter.format(dinner.due); } ]]></fx:Script> <fx:Declarations> <mx:DateFormatter id="dateFormatter" formatString="YYYY-MM-DD"/> <!--格式化日期的组件--> </fx:Declarations> <s:layout> <s:HorizontalLayout paddingLeft="10" paddingTop="10" paddingBottom="10" paddingRight="10"/> </s:layout> <mx:List dataProvider="{_dinners}" labelFunction="formatDinner" alternatingItemColors="[#EEEEEE, #FFFFFF]" variableRowHeight="true" wordWrap="true" width="250" height="150"/> <mx:DataGrid width="100%" height="150" dataProvider="{_dinners}"> <mx:columns> <!--数据列名同属性名--> <mx:DataGridColumn headerText="Name" dataField="name" width="150"/> <!--labelFunction 格式化当前列数据的函数--> <mx:DataGridColumn headerText="Due" dataField="due" width="100" labelFunction="formatDate"/> <mx:DataGridColumn headerText="Food" dataField="food"/> </mx:columns> </mx:DataGrid> </s:Application>