13

我想在启动时指定默认排序,但仍然允许用户通过单击列标题进行排序。遗憾的是,SortDirection 属性在设置时被忽略 - 即我们得到正确的列标题箭头,但没有排序。

手动单击标题,对数据进行正确排序,因此不是排序本身。这是我正在使用的简化版本:

<DataGrid ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=CurrentView}" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Header 1" Binding="{Binding ApplicationName}"/>
        <DataGridTextColumn Header="Header 2" 
               Binding="{Binding TotalTime}" SortDirection="Descending"/>
    </DataGrid.Columns>
</DataGrid>

更新:我还尝试按照建议将 SortDescriptions 添加到 ICollectionView,但效果不佳。这可能与我正在向集合中动态添加新项目的事实有关吗?即在启动时列表是空的并慢慢填充,也许排序描述只应用一次?

4

4 回答 4

14

看看这个MSDN 博客

从上面的链接:

DataGridColumn.SortDirection 实际上并不对列进行排序。
DataGridColumn.SortDirection 用于将 DataGridColumnHeader 中的可视箭头排列为向上、向下或不显示。要实际对列进行排序,而不是单击 DataGridColumnHeader,您可以通过编程方式设置 DataGrid.Items.SortDescriptions。

于 2011-12-19T02:03:47.747 回答
4

我对此没有任何个人经验,但我发现这篇很有帮助的文章

本质上,您需要将SortDescription添加到 DataGrid 绑定到的 CollectionViewSource 中。

于 2011-12-19T02:03:00.920 回答
2

这篇文章很有帮助。我能够使用它找到一个简单的解决方案。这是我的解决方案的一个片段。

XAML

        <DataGrid HorizontalAlignment="Stretch" VerticalAlignment="Stretch" 
            AutoGenerateColumns="False" ItemsSource="{Binding LogLister.Logs}"              
            IsReadOnly="True" >

            <DataGrid.Columns>                  

                <DataGridTextColumn Binding="{Binding TimeStampLocal}" Header="Time" x:Name="ColTimeStamp" />

                <DataGridTextColumn Binding="{Binding Text}" Header="Text"/>
            </DataGrid.Columns>
        </DataGrid>

代码

    // Using a DependencyProperty as the backing store for ViewModel.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty ViewModelProperty =
        DependencyProperty.Register("ViewModel", typeof(LogViewerViewModel), typeof(LogViewerControl),
           new UIPropertyMetadata(null,pf_viewModelChanged));

    private static void pf_viewModelChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
    {
        var control = (LogViewerControl)o;

        control.ColTimeStamp.SortDirection = ListSortDirection.Descending;

        var vm = e.NewValue as LogViewerViewModel;

        if (vm != null)
        {   
            ICollectionView collectionView = CollectionViewSource.GetDefaultView(vm.LogLister.Logs);
            collectionView.SortDescriptions.Add(new SortDescription("TimeStampLocal", ListSortDirection.Descending));
        }
    }
于 2012-02-06T22:12:27.273 回答
1

缺点是没有快速、简单的方法来做到这一点。我编写了自己的自定义排序器,它使用 ObservableCollections 上的 Move 方法。我重写了“DataGridSorting”事件并调用了我自己的方法来促进这一点。我不打算在这里发布代码,因为我认为这对你的问题来说太过分了。

我想说通过使用 CollectionViewSource 和 SortDescription(最初发布的 competent_tech)坚持我的上述评论。

于 2011-12-19T02:32:24.643 回答