2011-11-19 40 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; 
    } 
}