2017-05-31 48 views
0

關於this question和答案,我看着它,我知道用下面這行做一個泛型列表和數據網格之間編程綁定:綁定泛型列表到WPF DataGrid和排序它

LibraryView.SetValue(DataGrid.ItemsSourceProperty, _manager.Library.Songs); 

它工作,並可視化排序(雖然沒有在箭頭中的箭頭),但正如答案中提到的,它隱式使用ICollectionView。現在我的問題是如何反映排序綁定的數據源,在我的情況下通用列表。我已經發現如何用winforms做到這一點,但它更復雜,然後我期望,我不能將其轉換爲WPF。

在此先感謝

+0

爲什麼以及何時要對來源集合進行排序,即_manager.Library.Songs? – mm8

+0

因爲我使用該數據源作爲「播放列表」,所以順序應該與視圖相同,並且像點擊通常情況下那樣點擊柱狀標頭。 – JC97

+0

這個答案是爲winforms,但我不能將其轉換爲WPF(因爲我是新來的WPF):https://stackoverflow.com/a/2551416/5985593 – JC97

回答

1

如果您希望視圖對源集合進行排序,您可以將DataGridItemsSource屬性轉換爲您的集合類型並對其進行排序。當然,這需要您知道如何對排序集合進行排序以及您正在處理的源集合類型。

如果_manager.Library.SongsList<T>例如,你可以使用List<T>.Sort方法對它進行排序:

private void dg_Sorting(object sender, DataGridSortingEventArgs e) 
{ 
    var sourceCollection = dg.ItemsSource as List<Item>; 
    if (sourceCollection != null) 
    { 
     var sortDirection = e.Column.SortDirection; 
     switch (sortDirection) 
     { 
      default: 
      case ListSortDirection.Descending: 
       sortDirection = ListSortDirection.Ascending; 
       break; 
      case ListSortDirection.Ascending: 
       sortDirection = ListSortDirection.Descending; 
       break; 
     } 

     int direction = (sortDirection == ListSortDirection.Ascending ? 1 : -1); 
     string property = e.Column.SortMemberPath; 
     switch (property) 
     { 
      case nameof(Item.X): 
       sourceCollection.Sort((x, y) => x.X.CompareTo(y.X) * direction); 
       break; 
       //...and so on for all properties/columns 
     } 
    } 
} 

但在一般的視圖是不應該,它被綁定到源集合進行排序。

0

你可以自己創建ICollectionView和兩個直接您的控件的使用類ViewableCollectionhere綁定到它,例如和排序/過濾收集訪問ViewableCollection.View。這樣你只能排序一次,所有的控制都會反映這些變化。 DataGrid的默認排序行爲也可以在沒有額外代碼的情況下運行,您還可以通過簡單地在ViewableCollection.View上添加/清除當前的SortDescriptions來排序代碼隱藏。

如果您選擇使用此解決方案,請務必記住將ItemsSource屬性綁定到ViewableCollection.View而不是集合本身。

在表面上,它的工作方式類似於直接綁定到DataTableDataView,其格式來自兩個不同的控件。