【问题标题】:ColumnHeader sorting with a CollectionViewSource使用 CollectionViewSource 对 ColumnHeader 进行排序
【发布时间】:2015-06-17 13:30:03
【问题描述】:

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

如果绑定到 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>

【问题讨论】:

标签: c# wpf datagrid collectionviewsource


【解决方案1】:

您可以处理 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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-02
    • 2011-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-12
    • 1970-01-01
    • 2014-06-22
    相关资源
    最近更新 更多