private void ApplyColumnSort(GridViewColumnHeader header, GridViewColumn column, ListSortDirection direction) { var propertyName = GridViewSortBy.GetSortByKey(column); if (propertyName == null) { return; } // So AdornerLayer.GetAdornerLayer can apparently sometimes return null, even though we're calling it from // the Loaded event. Maybe it's because the Window hasn't yet fully loaded? Don't crash in this case // anyway: we won't show the little arrow, but that's not the end of the world. if (this.lastColumnHeader != null && this.lastAdorner != null) { AdornerLayer.GetAdornerLayer(this.lastColumnHeader)?.Remove(this.lastAdorner); } var adorner = new GridViewSortAdorner(header, direction); AdornerLayer.GetAdornerLayer(header)?.Add(adorner); var collectionView = CollectionViewSource.GetDefaultView(this.AssociatedObject.ItemsSource); collectionView.SortDescriptions.Clear(); collectionView.SortDescriptions.Add(new SortDescription(propertyName, direction)); collectionView.Refresh(); this.lastColumnHeader = header; this.lastDirection = direction; this.lastAdorner = adorner; }
private void PerformInitialSort() { var gridView = this.AssociatedObject.View as GridView; if (gridView == null) { return; } var initialSortColumn = gridView.Columns.FirstOrDefault(x => GridViewSortBy.GetIsInitiallySorted(x)); if (initialSortColumn == null) { return; } if (initialSortColumn.Header is GridViewColumnHeader header) { this.ApplyColumnSort(header, initialSortColumn, ListSortDirection.Ascending); } }