2010-07-09 165 views
0

我有一個silverlight數據網格,它綁定到顯示RowViewModels集合的PagedCollectionView。按索引對PagedCollectionView進行排序(使用Silverlight Datagrid)

每個RowVM都有一個CellViewModels集合,datagrid列是templatecolumns,它們的內容綁定到Cell [0] .Content,Cell [1] .Content等動態生成。這是因爲rowviewmodels被返回來自服務,並且可以包含任意數量的列和不同類型的內容。

這工作得很好,但是當啓用對數據網格中的列進行排序時遇到了問題。看起來DataGridColumns上的SortMemberPath屬性(它最終變成了一個SortDescription.PropertyName)不能用於包含索引的表達式,比如「Cells [1] .Content」。

有沒有人知道解決這個問題的方法?

回答

0

在這裏回答我自己的問題。

我解決了這個問題,通過將我生成的列上的SortMemberPath設置爲RowVM.Cells集合中的索引號,並向我的RowVM添加了SortOnMe屬性。

當用戶對數據網格進行排序時,它會將包含索引編號(從SortMemberPath獲取)的SortDescription添加到PagedCollectionView。我通過使用下面的方法監聽PagedCollectionView上的propertychanged事件來監視此情況。它添加了一個新的SortDescription,告訴PagedCollectionView在「SortOnMe」上進行排序,並複製數據以從相關單元格排序到row.SortOnMe。

private bool _currentlySorting; 
private void PagedCollectionView_PropertyChanged(object sender, PropertyChangedEventArgs e) 
{ 
    var pcv = (PagedCollectionView)sender; 
    int columnIndex = 0; 
    if (!_currentlySorting && e.PropertyName == "SortDescriptions" && pcv.SortDescriptions.Count == 1 && int.TryParse(pcv.SortDescriptions[0].PropertyName, out columnIndex)) { 
     _currentlySorting = true; 
     pcv.SortDescriptions.Add(new SortDescription("SortOnMe", pcv.SortDescriptions(0).Direction)); 
     foreach (RowViewModel row in pcv.SourceCollection) { 
      row.SortOnMe = row.Cells(columnIndex).Content; 
     } 
     _currentlySorting = false; 
    } 
} 

說實話,這是一個相當醜陋的解決方案。但是它很有用,而且我現在花了太多時間在我的牆上猛撞牆。

由於PagedCollectionView是一個密封類(爲什麼?!),我唯一能想到的做法是創建自己的PagedCollectionView並在那裏處理排序。

相關問題