今天一个同事问我一个需求,如何点击一个button, 使datagrid按特定的某列排序,于是简单写了个demo:
<?xml version="1.0"?>
<!-- DataGrid control example. -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
import mx.collections.XMLListCollection;
import mx.collections.Sort;
import mx.collections.SortField;
private function sortByColumn(sort:Boolean):void
{
arrColl.sort = new Sort();
var f:SortField = new SortField("idx", false, true);
f.descending = sort;
arrColl.sort.fields = [f];
arrColl.refresh();
}
]]>
</mx:Script>
<mx:ArrayCollection id="arrColl">
<mx:source>
<mx:Array>
<mx:Object idx="1" c1="One.1" c2="One.2" />
<mx:Object idx="2" c1="Two.1" c2="Two.2" />
<mx:Object idx="3" c1="Three.1" c2="Three.2" />
<mx:Object idx="4" c1="Four.1" c2="Four.2" />
<mx:Object idx="5" c1="Five.1" c2="Five.2" />
<mx:Object idx="6" c1="Six.1" c2="Six.2" />
<mx:Object idx="7" c1="Seven.1" c2="Seven.2" />
<mx:Object idx="8" c1="Eight.1" c2="Eight.2" />
<mx:Object idx="9" c1="Nine.1" c2="Nine.2" />
<mx:Object idx="10" c1="Ten.1" c2="Ten.2" />
<mx:Object idx="11" c1="Eleven.1" c2="Eleven.2" />
<mx:Object idx="12" c1="Twelve.1" c2="Twelve.2" />
<mx:Object idx="13" c1="Thirteen.1" c2="Thirteen.2" />
</mx:Array>
</mx:source>
</mx:ArrayCollection>
<mx:Panel title="DataGrid Control Example" height="100%" width="100%"
paddingTop="10" paddingLeft="10" paddingRight="10">
<mx:Label width="100%" color="blue"
text="Select a row in the DataGrid control."/>
<mx:DataGrid id="dg" width="100%" height="100%" rowCount="5" dataProvider="{arrColl}">
<mx:columns>
<mx:DataGridColumn dataField="idx" headerText="Name"/>
<mx:DataGridColumn dataField="c1" headerText="Phone"/>
<mx:DataGridColumn dataField="c2" headerText="Email"/>
</mx:columns>
</mx:DataGrid>
<mx:CheckBox id="srotChk"/>
<mx:Button id="sortBtn" label="sort" click="sortByColumn(srotChk.selected)"/>
</mx:Panel>
</mx:Application>
<?xml version="1.0" encoding="utf-8"?>
<mx:Application
xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical"
creationComplete="setDataProvider()">
<mx:Script>
<![CDATA[
import mx.collections.XMLListCollection;
[Bindable]
private var xmlOriginal : XML =
<root>
<item name="Alpha" letter="Z"/>
<item name="Beta" letter="P"/>
<item name="Gamma" letter="X"/>
<item name="Delta" letter="P"/>
</root>
private var xmlUpdated : XML =
<root>
<item name="Alpha" letter="F"/>
<item name="Beta" letter="U"/>
<item name="Gamma" letter="A"/>
<item name="Delta" letter="P"/>
<item name="Epsilon" letter="F"/>
</root>
private function setDataProvider() : void
{
dataGrid.dataProvider = new XMLListCollection( xmlOriginal..item );
}
]]>
</mx:Script>
<mx:DataGrid
id="dataGrid"/>
<mx:Button
label="Simulate Update"
click="XMLListCollection( dataGrid.dataProvider ).source = xmlUpdated..item"/>
</mx:Application>
简单替换