<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" initialize= "initDP();" width="550" height="400"> <mx:Script> <!--[CDATA[ import mx.events.DataGridEvent; import mx.collections.*; private var myDPColl:ArrayCollection; [Bindable] //Sort对象处理排序 private var sortA:Sort; // 可进行排序的类别 private var sortByProductName:SortField; private var sortByProductType:SortField; private var sortByProductPrice:SortField; // Data Provider private var myDP:Array = [ {product:'Thinkpad', type:'T61',price:22000}, {product:'Thinkpad', type:'T61P',price:26000}, {product:'Thinkpad', type:'X61',price:14000}, {product:'Apple', type:'MacBook AIR',price:16000}, {product:'Apple', type:'MacBook Pro',price:23000} ]; //初始化排序的Data Grid组件 private function initDP():void { myDPColl = new ArrayCollection(myDP); //通过ArrayCollection构建排序 sortA = new Sort(); sortByProductName = new SortField("product",true); sortByProductType = new SortField("type", true); sortByProductPrice = new SortField("price",true); sortA.fields = [sortByProductName, sortByProductType, sortByProductPrice]; myDPColl.sort=sortA; //刷新集合,是排序生效 myDPColl.refresh(); //定义Label显示排序状态 tSort0.text = "排序1:产品名称"; tSort1.text = "排序2:型号"; tSort2.text = "排序3:价格"; myGrid.dataProvider=myDPColl; myGrid.rowCount=myDPColl.length +1; } private function headRelEvt(event:DataGridEvent):void { sortA.fields[2] = sortA.fields[1]; tSort2.text = "排序3:" + sortA.fields[2].name; sortA.fields[1] = sortA.fields[0]; tSort1.text = "排序2: " + sortA.fields[1].name; if (event.columnIndex==0) { sortA.fields[0] = sortByProductName; } else if (event.columnIndex==1) { sortA.fields[0] = sortByProductType; } else if (event.columnIndex==2) { sortA.fields[0] = sortByProductPrice; } tSort0.text = "排序1:" + sortA.fields[0].name; // Apply the updated sort fields and re-sort. myDPColl.sort=sortA; myDPColl.refresh(); event.preventDefault(); } ]]--> </mx:Script> <mx:DataGrid id="myGrid" fontSize="12" width="100%" headerRelease= "headRelEvt(event);"> <mx:columns> <mx:DataGridColumn dataField="product" headerText="产品"/> <mx:DataGridColumn dataField="type" headerText="型号"/> <mx:DataGridColumn dataField="price" headerText="价格"/> </mx:columns> </mx:DataGrid> <mx:VBox fontSize="12"> <mx:Label id="tSort0" text="排序1:"/> <mx:Label id="tSort1" text="排序2:"/> <mx:Label id="tSort2" text="排序3:"/> </mx:VBox> </mx:Application>