DataGrid排序不起作用

时间:2016-09-20 10:34:09

标签: wpf xaml sorting wpfdatagrid

我的TabControlTabItemDataGrid

<TabControl Background="{DynamicResource StandardBackgroundColor}" 
            Grid.Row="2" Grid.Column="1"
            BorderBrush="{DynamicResource StandardBorderColor}" 
            DataContext="{Binding ChartViewModel}">


<TabItem Header="{lex:Loc Data}">
           <DataGrid Name="TagGrid" ItemsSource="{Binding UnionAllSerie}" 
                     ColumnWidth="*" Background="#CCCCCC">
                    <DataGrid.Columns>
                        <DataGridTextColumn Header="Name" Binding="{Binding Name}" />
                        <DataGridTextColumn Header="{lex:Loc time}" SortDirection="Descending"
                                            Binding="{Binding X, Converter={StaticResource OleDateToDateTimeConverter}, StringFormat=\{0:dd/MM/yy HH:mm\}}" />
                        <DataGridTextColumn Header="{lex:Loc Measure}"
                                            Binding="{Binding Y}" />
                    </DataGrid.Columns>
            </DataGrid>
</TabItem>

我的UnionAllSerie声明如下:

public ObservableCollection<Data> UnionAllSerie { get; set; } = new ObservableCollection<Data>();

根据在窗口上执行的操作填充此数据集。我想要的是让Grid自动按第二列排序,它代表日期。

有人知道我做错了什么或错过了吗? 谢谢!

1 个答案:

答案 0 :(得分:2)

在Datagrid列上设置SortDirection实际上并不对列进行排序。 (有关详细信息,请参阅here。)

我建议使用CollectionViewSource,它具有为您的目的而构建的功能。 结果应如下所示:

<Window.Resources>
    <CollectionViewSource x:Key="UnionAllSerieViewSource" Source="{Binding UnionAllSerie}">
        <CollectionViewSource.SortDescriptions>
            <scm:SortDescription PropertyName="X" Direction="Descending"/>
        </CollectionViewSource.SortDescriptions>
    </CollectionViewSource>
</Window.Resources>
...
<DataGrid Name="TagGrid" ItemsSource=""{Binding Source={StaticResource UnionAllSerieViewSource}}"" 
                 ColumnWidth="*" Background="#CCCCCC">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Name" Binding="{Binding Name}" />
                <DataGridTextColumn Header="{lex:Loc time}" SortDirection="Descending"
                                    Binding="{Binding X, Converter={StaticResource OleDateToDateTimeConverter}, StringFormat=\{0:dd/MM/yy HH:mm\}}" />
                    <DataGridTextColumn Header="{lex:Loc Measure}"
                                    Binding="{Binding Y}" />
            </DataGrid.Columns>
</DataGrid>

有关如何对CollectionViewSources进行排序的详细信息,请参阅this msdn article