WPF 数据网格按所选列自动排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34421719/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 13:35:55  来源:igfitidea点击:

WPF datagrid automatic sorting by chosen column

c#wpfxamldatagrid

提问by Marcin Zdunek

currently I am working on WPF's datagrid. I got an issue with automatic sorting. Here is my xaml:

目前我正在研究 WPF 的数据网格。我遇到了自动排序的问题。这是我的 xaml:

<DataGrid x:Name="customTasksDataGrid" Margin="10,10,10,38" Grid.Column="1" IsReadOnly="True" AutoGenerateColumns="False">
<DataGrid.Columns>
    <DataGridTextColumn Header="ID" Binding="{Binding ID}"/>
    <DataGridTextColumn Header="Client" Binding="{Binding Client.Names}"/>
    ...
    <DataGridTextColumn Header="DueDate" Binding="{Binding DueDate, StringFormat=\{0:dd.MM.yy HH:mm\}}" SortDirection="Ascending">
        <DataGridTextColumn.ElementStyle>
            <Style TargetType="{x:Type TextBlock}">
                <Setter Property="Foreground" Value="{Binding Path=., Converter={StaticResource converter}}"/>
            </Style>
        </DataGridTextColumn.ElementStyle>
    </DataGridTextColumn>
    ...
</DataGrid.Columns>

The problem is: when I update my datagrid's ItemsSource, the datagrid is sorted by IDcolumn, not DueDateas desirable. How to implement autosorting by DueDatewhen any update action on my datagrid is performed?

问题是:当我更新我的数据网格的 ItemsSource 时,数据网格按ID列排序,而不是DueDate理想的。如何在DueDate对我的数据网格执行任何更新操作时实现自动排序?

I tried with: [ImplementPropertyChanged]tag from PropertyChanged.Fodyand put it before my CustomTaskclass, but this approach was not working at all ( don't even know if it is needed).

我尝试过:[ImplementPropertyChanged]标记 fromPropertyChanged.Fody并将其放在我的CustomTask课前,但这种方法根本不起作用(甚至不知道是否需要)。

EDIT:

编辑:

It can be done with:

可以通过以下方式完成:

customTasksDataGrid.ItemsSource = model;
customTasksDataGrid.Items.SortDescriptions.Add(new SortDescription("DueDate", ListSortDirection.Ascending));

采纳答案by jHilscher

You can simply sort the datagrid in Code Behind:

您可以简单地在代码隐藏中对数据网格进行排序:

datagrid.Items.SortDescriptions.Add(new SortDescription("DueDate", ListSortDirection.Ascending));