// Evaluates the given ListView's AttachedProperties.SortInstructions and calls EstablishCodedSortOrder public static void EstablishInitialSortOrder(this ListView listView, string sortInstructions = null) { if (sortInstructions == null) { sortInstructions = ListViewGridViewHelper.GetSortInstructions(listView); } listView.EstablishCodedSortOrder(sortInstructions, ListSortDirection.Ascending); }
// expects a sortInstructions string like "↓GroupKey↑Group2↕Item" // ↓ = sort ascending (fix), ↑ = sort descending (fix), ↕ = column sorting (toggleable) // public static ListSortDirection EstablishCodedSortOrder(this ListView listView, string sortInstructions, ListSortDirection?overrideToggleDirection = null) { var dataView = CollectionViewSource.GetDefaultView(listView.ItemsSource); var establishedColumnDirection = ListSortDirection.Ascending; if (dataView != null && dataView.SortDescriptions != null && sortInstructions != null) { dataView.SortDescriptions.Clear(); foreach (Match m in Regex.Matches(sortInstructions, @"([↓↑↕])([^↓↑↕]+)")) { var dirCode = m.Groups[1].Value; var fieldCode = m.Groups[2].Value; if (dirCode == "↓") { dataView.SortDescriptions.Add(new SortDescription(fieldCode, ListSortDirection.Ascending)); } else if (dirCode == "↑") { dataView.SortDescriptions.Add(new SortDescription(fieldCode, ListSortDirection.Descending)); } else { string lastColumnSorted = ListViewGridViewHelper.GetLastColumnSorted(listView); ListSortDirection?lastSortDirection = ListViewGridViewHelper.GetLastSortDirection(listView); if (overrideToggleDirection.HasValue) { establishedColumnDirection = overrideToggleDirection.Value; } else if (lastColumnSorted != null && fieldCode == lastColumnSorted && lastSortDirection.HasValue && lastSortDirection.Value == ListSortDirection.Ascending) { establishedColumnDirection = ListSortDirection.Descending; } dataView.SortDescriptions.Add(new SortDescription(fieldCode, establishedColumnDirection)); ListViewGridViewHelper.SetLastColumnSorted(listView, fieldCode); ListViewGridViewHelper.SetLastSortDirection(listView, establishedColumnDirection); } } dataView.Refresh(); } return(establishedColumnDirection); }