关于Flex的DataGrid的应用拓展(四)

Flex的Datagrid在程序中得应用非常广泛,使用起来也非常的简单。但功能还是不够,大家还要自己去实现一些自己的功能。比如排序,它只支持字符串排序,而面向日期或者时间的排序他就无能为力了。下面介绍如何实现数字和日期的自动排序。
1)通过实现DatagridColumn的继承,添加排序方法。
package
{
    import mx.controls.dataGridClasses.DataGridColumn;
    import mx.utils.ObjectUtil;
    
    public class SystemSortDatagridColumn extends DataGridColumn
    {
        public function SystemSortDatagridColumn(columnName:String=null)
        {
            super(columnName);
            if(this.sortCompareFunction!=null){
                this.sortCompareFunction=customSortColumn(this.dataField);
            }
        }
        
        
        
        public static function customSortColumn(sortField:String):Function{
                return function(item1:Object, item2:Object):int{
                    if(item1 is Number && item2 is Number)
                    {
                        return ObjectUtil.numericCompare(item1 as Number,item2 as Number);
                    }else if(item1 is Date && item2 is Date){
                        return ObjectUtil.dateCompare(item1 as Date,item2 as Date);
                    }else{
                       return  ObjectUtil.compare(item1 as String,item2 as String);
                    }
                   
                }
        }
    }
}

2.测试demo:
<?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" minWidth="955" minHeight="600" creationComplete="application1_creationCompleteHandler(event)" xmlns:local="*">
    <fx:Declarations>
        <!-- 将非可视元素(例如服务、值对象)放在此处 -->
    </fx:Declarations>
    <fx:Script>
        <![CDATA[
            import mx.collections.ArrayCollection;
            import mx.collections.ArrayList;
            import mx.events.FlexEvent;
            
            [Bindable]
         public   var ac:ArrayCollection=new ArrayCollection();
            
            protected function application1_creationCompleteHandler(event:FlexEvent):void
            {
                ac.addItem({"name":"fu1" ,"age":21,"date":new Date()});
                ac.addItem({"name":"fu2" ,"age":1});
                ac.addItem({"name":"fu2" ,"age":111});
                ac.addItem({"name":"fu3" ,"age":"fu"});
                ac.addItem({"name":"fu4" ,"age":"fu1"});
            }
            
        ]]>
    </fx:Script>
    <mx:DataGrid dataProvider="{ac}">
        <mx:columns>
            <local:SystemSortDatagridColumn headerText="Name" dataField="name" />
            <local:SystemSortDatagridColumn headerText="Age" dataField="age" />
        </mx:columns>
    </mx:DataGrid>
    
</s:Application>

你可能感兴趣的:(datagrid)