Windows Phone 8的LongListSelector控制項按拼音分組主要有兩種方法,一個是在資料來源裡手工指定拼音首字母欄位,作為index,這種方法效率高但會造成資料冗餘不宜維護。另一個就是我今天介紹的方法,來自MSDN,雖然官網例子是針對是英文資料的首字母分組,但其實稍微改一下還是是支援中文的。
publicclassAlphaKeyGroup<T> : List<T>{ ///<summary> /// The delegate that is used to get the key information. ///</summary> ///<param name="item">An object of type T</param> ///<returns>The key value to use for this object</returns> publicdelegatestringGetKeyDelegate(T item); ///<summary> /// The Key of this group. ///</summary> publicstring Key { get; privateset; } ///<summary> /// Public function Object() { [native code] }. ///</summary> ///<param name="key">The key for this group.</param> publicAlphaKeyGroup(string key) { Key = key; } ///<summary> /// Create a list of AlphaGroup<T> with keys set by a SortedLocaleGrouping. ///</summary> ///<param name="slg">The </param> ///<returns>Theitems source for a LongListSelector</returns> privatestatic List<AlphaKeyGroup<T>> CreateGroups(SortedLocaleGrouping slg) { return slg.GroupDisplayNames.Select(key => new AlphaKeyGroup<T>(key)).ToList(); } ///<summary> /// Create a list of AlphaGroup<T> with keys set by a SortedLocaleGrouping. ///</summary> ///<param name="items">The items to place in the groups.</param> ///<param name="ci">The CultureInfo to group and sort by.</param> ///<param name="getKey">A delegate to get the key from an item.</param> ///<param name="sort">Will sort the data if true.</param> ///<returns>An items source for a LongListSelector</returns> publicstatic List<AlphaKeyGroup<T>> CreateGroups(IEnumerable<T> items, CultureInfo ci, GetKeyDelegate getKey, bool sort) { var slg = new SortedLocaleGrouping(ci); var list = CreateGroups(slg); foreach (var item in items) { var index = 0; if (slg.SupportsPhonetics) { //check if your database has yomi string for item //if it does not, then do you want to generate Yomi or ask the user for this item. //index = slg.GetGroupIndex(getKey(Yomiof(item))); } else { index = slg.GetGroupIndex(getKey(item)); } if (index >= 0 && index < list.Count) { list[index].Add(item); } } if (!sort) return list; foreach (vargroupin list) { @group.Sort((c0, c1) => ci.CompareInfo.Compare(getKey(c0), getKey(c1))); } return list; }}