ColumnHeader sorting with a CollectionViewSource

本文关键字:CollectionViewSource with sorting ColumnHeader | 更新日期: 2023-09-27 17:56:41

我有一个数据绑定到集合视图源的数据网格。如果我将数据网格绑定到列表我可以通过单击列标题自动对数据网格的列进行排序。

如果绑定到 CollectionViewSource,则列标题仍显示为 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>

ColumnHeader sorting with a CollectionViewSource

您可以处理 DataGrid 的 Sorting 事件,并在代码隐藏中创建适当的 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);
}
相关文章:
  • 没有找到相关文章