Flex DataGrid 默认情况下的排序方式

DataGridColumn的属性sortCompareFunction和sortDescending是点击列头后的排序方式,而要确定默认情况下的排序方式是无效的。那么怎么办?

查看datagrid的官方代码就会知道如何给datagrid默认排序,下面是官方代码:

 private function updateSortIndexAndDirection():void
    {
        // Don't show sort indicator if sortableColumns is false or if the
        // column sorted on has sortable="false"

        if (!sortableColumns)
        {
            lastSortIndex = sortIndex;
            sortIndex = -1;

            if (lastSortIndex != sortIndex)
                invalidateDisplayList();

            return;
        }

        if (!dataProvider)
            return;

        var view:ICollectionView = ICollectionView(dataProvider);
        var sort:Sort = view.sort;
        if (!sort)
        {
            sortIndex = lastSortIndex = -1;
            return;
        }

        var fields:Array = sort.fields;
        if (!fields)
            return;

        if (fields.length != 1)
        {
            lastSortIndex = sortIndex;
            sortIndex = -1;

            if (lastSortIndex != sortIndex)
                invalidateDisplayList();

            return;
        }

        // fields.length == 1, so the collection is sorted on a single field.
        var sortField:SortField = fields[0];
        var n:int = _columns.length;
        sortIndex = -1;
        for (var i:int = 0; i < n; i++)
        {
            if (_columns[i].dataField == sortField.name)
            {
                sortIndex = _columns[i].sortable ? i : -1;
                sortDirection = sortField.descending ? "DESC" : "ASC";
                return;
            }
        }
    }

 

可以这样实现:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="init()">
    <mx:Script>
    <![CDATA[
    import mx.collections.SortField;
    import mx.collections.Sort;
    import mx.utils.ObjectUtil;
    import mx.collections.ArrayCollection;
    [Bindable]
    private var adg:ArrayCollection = new ArrayCollection([{name:"张三华",age:15,sex:"男"},
                                                           {name:"李四国",age:45,sex:"男"},
                                                           {name:"王七花",age:24,sex:"女"},
                                                           {name:"赵华柳",age:17,sex:"女"},
                                                           {name:"田三华",age:33,sex:"男"},]);
                                                          
                                                          
    private function init():void{
    adg.sort = new Sort();
    adg.sort.fields = [new SortField("age",false,true)];
    adg.refresh();
    dg.dataProvider = adg;
    }

    private function sortRanges(obj1:Object,obj2:Object):int{
    var value1:Number = obj1.age;
    var value2:Number = obj2.age;
    if(value1 > value2 ){
    return 1;
    }else if(value1 < value2 ){
    return -1;
    }else{
    return 0;
    }
    }            
    private function dataFilter():void{
    if(adg.filterFunction == null){
    adg.filterFunction = dataFilter2;
    }
    adg.refresh();
    }          
    private function dataFilter2(item:Object):Boolean{
    var bool:Boolean = true;
    var it:String = item["name"];
    var filter:String = ti.text;
    if(!it || it.toLowerCase().indexOf(filter.toLowerCase()) < 0){
    bool = false;
    }
    return bool;
    }      
    private function sortCompare(obj1:Object,obj2:Object):int{
    return ObjectUtil.numericCompare(obj1.age,obj2.age);
    }                
    ]]>
    </mx:Script>
    <mx:DataGrid id="dg"  x="89" y="46" width="552" height="160">
    <mx:columns>
    <mx:DataGridColumn  headerText="name" dataField="name"/>
    <mx:DataGridColumn headerText="age" dataField="age"/>
    <mx:DataGridColumn headerText="sex" dataField="sex" />
    </mx:columns>
    </mx:DataGrid>
    <mx:Form>
    <mx:FormItem>
    <mx:TextInput id="ti" change="dataFilter()"/>
    </mx:FormItem>
    </mx:Form>
</mx:Application>


重点是黑体字部分,SortField第一个参数是排序的字段,第二个参数用来确定是否区分大小写,第三个参数表示是否按降序排列。 

 参考官方SortField构造函数就明白了:

 /**
     *  Constructor.
     *
     *  @param name The name of the property that this field uses for
     *              comparison.
     *              If the object is a simple type, pass <code>null</code>.
     *  @param caseInsensitive When sorting strings, tells the comparitor
     *              whether to ignore the case of the values.
     *  @param descending Tells the comparator whether to arrange items in
     *              descending order.
     *  @param numeric Tells the comparitor whether to compare sort items as
     *              numbers, instead of alphabetically.
     * 
     *  @langversion 3.0
     *  @playerversion Flash 9
     *  @playerversion AIR 1.1
     *  @productversion Flex 3
     */

 public function SortField(name:String = null,
                              caseInsensitive:Boolean = false,
                              descending:Boolean = false,
                              numeric:Object = null)
    {
        super();

        _name = name;
        _caseInsensitive = caseInsensitive;
        _descending = descending;
        _numeric = numeric;
        _compareFunction = stringCompare;
    }

 

 

 

下面补充: 点击DataGridColumn列头后的排序方式的原因(官方代码),关注属性sortCompareFunction和sortDescending

   /**
     *  @private
     */
    private function headerReleaseHandler(event:DataGridEvent):void
    {
        if (!event.isDefaultPrevented())
        {
            manualSort = true;
            sortByColumn(event.columnIndex);
            manualSort = false;
        }
    }


    /**
     *  @private
     */
    private function sortByColumn(index:int):void
    {
        var c:DataGridColumn = columns[index];
        var desc:Boolean = c.sortDescending;

        // do the sort if we're allowed to
        if (c.sortable)
        {
            var s:Sort = collection.sort;
            var f:SortField;
            if (s)
            {
                s.compareFunction = null;
                // analyze the current sort to see what we've been given
                var sf:Array = s.fields;
                if (sf)
                {
                    for (var i:int = 0; i < sf.length; i++)
                    {

                        if (sf[i].name == c.dataField)
                        {
                            // we're part of the current sort
                            f = sf[i]
                            // flip the logic so desc is new desired order
                            desc = !f.descending;
                            break;
                        }
                    }
                }
            }
            else
                s = new Sort;

            if (!f)
                f = new SortField(c.dataField);


            c.sortDescending = desc;
            var dir:String = (desc) ? "DESC" : "ASC";
            sortDirection = dir;

            // set the grid's sortIndex
            lastSortIndex = sortIndex;
            sortIndex = index;
            sortColumn = c;

            // if you have a labelFunction you must supply a sortCompareFunction
            f.name = c.dataField;
            if (c.sortCompareFunction != null)
            {
                f.compareFunction = c.sortCompareFunction;
            }
            else
            {
                f.compareFunction = null;
            }
            f.descending = desc;
            s.fields = [f];
        }
        collection.sort = s;
        collection.refresh();

    }

 

你可能感兴趣的:(object,function,datagrid,Flex,application,import)