2015-06-17 53 views
2

我有一個數據綁定到集合視圖源的DataGrid。 如果我將DataGrid綁定到列表<T>我可以通過單擊列標題自動排列我的DataGrid的列。ColumnHeader使用CollectionViewSource排序

如果綁定到CollectionViewSource,那麼列標題仍會顯示指示爲DataGrid將排序,但它不排序。 我該如何實現相同的功能?

這是我的DataGrid:

<DataGrid Grid.Row="1" SelectedItem="{Binding SelectedItem}" 
        SelectionMode="Single" SelectionUnit="FullRow" AutoGenerateColumns="False" ItemsSource="{Binding CurrentErrorsViewSource.View}" 
        CanUserSortColumns="True" CanUserAddRows="False" CanUserDeleteRows="False" CanUserReorderColumns="False" IsReadOnly="True"> 
      <DataGrid.Columns> 
       <DataGridTemplateColumn CanUserResize="False"> 
        <DataGridTemplateColumn.CellTemplate> 
         <DataTemplate> 
          <ContentControl Template="{StaticResource ErrorRemoteControl}" Foreground="{StaticResource GlyphBrush}" /> 
         </DataTemplate> 
        </DataGridTemplateColumn.CellTemplate> 
       </DataGridTemplateColumn> 
       <DataGridTextColumn Header="{userInterface:Translation Description}" Binding="{Binding Path=(viewModels:ErrorItemViewModel.ErrorInformation).Description}" Width="Auto" /> 
       <DataGridTextColumn Header="{userInterface:Translation Code}" Binding="{Binding Path=(viewModels:ErrorItemViewModel.ErrorCode)}" Width="Auto" /> 
      </DataGrid.Columns> 
     </DataGrid> 
+0

你見過? https://social.msdn.microsoft.com/Forums/vstudio/en-US/0075ec8b-71d8-43e8-af08-818c09548d41/sorting-an-ef-collection-in-datagrid – Arie

回答

2

你可以處理Sorting事件的DataGrid,並在代碼隱藏創建此時,相應的SortDescription對象並將其添加到您的CollectionViewSource的SortDescriptions集合。

void SortHandler(object sender, DataGridSortingEventArgs e) 
{ 
    var collectionViewSource = (sender as DataGrid).ItemsSource as CollectionViewSource; 

    var propertyName = e.Column.SortMemberPath; 
    var sortDirection = ListSortDirection.Ascending; 

    foreach (var sortDescription in collectionViewSource.SortDescriptions) 
     if (sortDescription.PropertyName == propertyName && 
      sortDescription.Direction == ListSortDirection.Ascending) 
     { 
      sortDirection = ListSortDirection.Descending; 
      break; 
     } 

    var sortDescription = new SortDescription() 
    { 
     PropertyName = propertyName, 
     Direction = sortDirection 
    }; 

    collectionViewSource.SortDescriptions.Clear(); 
    collectionViewSource.SortDescriptions.Add(sortDescription); 
} 
相關問題