2011-11-19 42 views
2

是否可以在Silverlight4中的PagedCollectionView中自定義排序? 在我看來,我有可能根據給定的屬性對這個集合進行排序。我也可以設置,如果我想排序收集升序或降序。不過,我看不出有可能設置自定義排序 - 使用某種比較器或類似的東西。PagedCollectionView自定義排序

最簡單的排序,可以以這種方式實現

PlayerPagedCollection = new PagedCollectionView(); 
PlayerPagedCollection.SortDescriptions.Clear(); 
PlayerPagedCollection.SortDescriptions.Add(new System.ComponentModel.SortDescription("Name",ListSortDirection.Ascending)); 

是否有可能以某種方式設置自定義排序?我需要使它在Silverlight4上工作

回答

0

額外的複雜性並不理想,但這對我很有用。

public class YourViewModel 
{ 
    private YourDomainContext context; 
    private IOrderedEnumerable<Person> people; 
    private PagedCollectionView view; 
    private PersonComparer personComparer; 

    public YourViewModel() 
    { 
     context = new YourDomainContext(); 
     personComparer = new PersonComparer() 
     { 
      Direction = ListSortDirection.Ascending 
     }; 
     people = context.People.OrderBy(p => p, personComparer); 
     view = new PagedCollectionView(people); 
    } 

    public void Sort() 
    { 
     using (view.DeferRefresh()) 
     { 
      personComparer.Direction = ListSortDirection.Ascending; 

      //this triggers the IOrderedEnumerable to resort 
      FlightTurnaroundProcessesView.SortDescriptions.Clear(); 
     } 
    } 
} 

public class PersonComparer : IComparer<Person> 
{ 
    public ListSortDirection Direction { get; set; } 

    public int Compare(Person x, Person y) 
    { 
     //add any custom sorting here 
     return x.CompareTo(y) * GetDirection(); 
    } 

    private int GetDirection() 
    { 
     return Direction == ListSortDirection.Ascending ? 1 : -1; 
    } 
}