2

我有一個帶有HierarchicalCollectionView作爲其dataProvider的AdvancedDataGrid。當我用正在處理的數據集查看網格,然後單擊我希望排序的列的標題時,一切正常。它按照我期望的方式分層次排列。如何使用分層數據對AdvancedDataGrid進行排序?

我現在要做的是讓網格在顯示給用戶時已經排序。有沒有辦法做到這一點編程?我不能爲我的生活弄清楚如何做到這一點,並明確這是可能的,因爲在AdvancedDataGrid有這個建於

編輯 - 順便說一句,我已經試過這樣:

var myData:HierarchicalCollectionView = new HierarchicalCollectionView(theDataSource); 

// Works fine using only the line above and clicking the header to sort. 
// This is the part that I tried adding: 
var sort:Sort = new Sort(); 

sort.fields = [new SortField("startDate")]; 

myData.sort = sort; 
myData.refresh(); 

這似乎做東西儘可能排序,但它不會按照與單擊列標題相同的方式排序它。順便說一句,「startDate」是theDataSource中某個對象的屬性。

回答

2

看起來你想要對日期進行排序。 Sort無法做到這一點。你必須使用compareFunction

如果你的對象是Date類型的它很容易:

var sortField:SortField = new SortField("startDate"); 
sortField.compareFunction = ObjectUtil.dateCompare; 

如果您的列包含(從http://blog.flexexamples.com/2007/08/12/sorting-date-columns-in-a-datagrid/代碼示例)日期,你得先解析這些字符串:

private function date_sortCompareFunc(itemA:Object, itemB:Object):int 
{ 
    /* Date.parse() returns an int, but 
     ObjectUtil.dateCompare() expects two 
     Date objects, so convert String to 
     int to Date. */ 
    var dateA:Date = new Date(Date.parse(itemA)); 
    var dateB:Date = new Date(Date.parse(itemB)); 
    return ObjectUtil.dateCompare(dateA, dateB); 
} 

var sortField:SortField = new SortField("startDate"); 
sortField.compareFunction = date_sortCompareFunc; 

然後就像你在你的例子中那樣使用sortField。這應該很好。

+0

我不確定當對象的類型是Date時是否需要compareFunction。目前無法測試... – 2011-03-29 22:00:27

+0

它不需要compareFunction。我不小心加入了新的SortField(「startDate」,true)',但是我認爲日期不會區分大小寫,所以改變它去除'true'就行了。 – Ocelot20 2011-03-30 15:36:56

1

您可以創建一個新的高級數據網格排序事件並在設置分層數據後在網格上調度它(不幸的是,我必須使用callLater來給網格時間來處理內部的集合似乎分配到ADG的dataProvider有時異步)

 var advancedDataGridEvent : AdvancedDataGridEvent = new AdvancedDataGridEvent(AdvancedDataGridEvent.SORT, false, true); 

     advancedDataGridEvent.columnIndex = columnIndex; 
     advancedDataGridEvent.dataField = dataField; 

     dispatchEvent(advancedDataGridEvent); 

此代碼是ADG的擴展,所以你會希望dispatchEvent實際上是在你的網格的情況下,如果你不創建一個擴展。

而且從代碼的註釋:

  //setting sortDescending=true on a column does not work as expected. so, until a solution 
      //is found, this works just as well. the event that is dispatch just tells the column 
      //to reset. so, one resorts ascending (the default), while a second resorts descending. 
      //however, this second is only dispatched if defaultSortDesc is true on the grid. 
      if (defaultSortDesc) 
      { 
       dispatchEvent(advancedDataGridEvent); 
      } 

將分派事件兩次翻轉排序。

相關問題