DataGrid SortDirection被忽略

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

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

      

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

看看这个MSDN博客

从上面的链接:

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

我对此没有任何个人经验,但我发现这篇相当有用的文章 。

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

这篇文章非常有帮助。 我能够用它来找到一个简单的解决方案。 以下是我的解决方案的片段。

XAML

        

  // 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)); } } 

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

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