2013-02-12 127 views

回答

0

这是可能的。 ObservableCollection不提供排序选项,因此您必须创建一个新的集合,该集合按所选属性排序。请参阅以下示例代码。有关其他排序选项,请阅读博客文章hereanother stackoverflow thread

// TODO: Create an appropriate data model for your problem domain to replace the sample data 
var group = SampleDataSource.GetGroup((String)navigationParameter); 
this.DefaultViewModel["Group"] = group; 
//this.DefaultViewModel["Items"] = group.Items; 

// Sort items by creating a new collection 
ObservableCollection<SampleDataItem> grpSorted = new ObservableCollection<SampleDataItem>(
group.Items.OrderBy(grp => grp.Title)); 

this.DefaultViewModel["Items"] = grpSorted; 
+0

这是C#,但根据到问题上的标签,他正在寻找一个JavaScript/WinJS解决方案。 – 2013-02-20 17:53:42

1

我在同一个问题上挣扎,既没有找到有用的例子,也没有提示。然后我开始将SortedListProjection和GroupedSortedListProjection结合起来,最终使它工作。

我的用例是按照字母顺序排列的组,按升序排列,但在一个组内,按时间戳顺序排列。

这是我如何设置它的JavaScript文件中:

var list = new WinJS.Binding.List(); // list gets populated later in the code 
var sortedList = list.createSorted(compareItems); 
var groupedList = list.createGrouped(getGroupKey, getGroupData, compareGroups); 

WinJS.Namespace.define("my.stuff", { 
    sortedList: sortedList, 
    groupedList: groupedList 
}); 

最重要的事情是保持与分组同步排序的项目。因此项目排序功能正在调用分组功能。

下面是用于排序和分组的所有四个功能:

compareItems = function (leftItem, rightItem) { 
    let leftKey = getGroupKey(leftItem); 
    let rightKey = getGroupKey(rightItem); 
    let compare = compareGroups(leftKey, rightKey); 
    if (compare == 0) { // if keys are equal compare timestamps 
     return leftItem.timestamp < rightItem.timestamp ? 1 
      : leftItem.timestamp > rightItem.timestamp ? -1 : 0; 
    } 
    return compare; 
}; 

getGroupKey = function (item) { 
    return item.name + item.category; 
}; 

getGroupData = function (item) { 
    return { 
    name: item.name + " (" + item.category + ")" 
    }; 
}; 

compareGroups = function (leftKey, rightKey) { 
    return leftKey.toUpperCase().localeCompare(rightKey); 
}; 

最后,两个列表为ListView的合并声明:

<div id="dataDeliveriesList" class="hidden" 
    data-win-control="WinJS.UI.ListView" 
    data-win-options="{ 
     itemDataSource: my.stuff.sortedList.dataSource, 
     itemTemplate: select('#itemTemplate'), 
     groupDataSource: my.stuff.groupedList.groups.dataSource, 
     groupHeaderTemplate: select('#groupHeaderTemplate'), 
     layout: { 
      type: WinJS.UI.ListLayout 
     } 
    }"> 
</div> 
+0

只有我自己才明白,你可以利用排序功能中的分组功能,并保持密钥生成和比较同步: – phileas74 2016-11-22 23:25:55

相关问题