static void SetDataGridEnvironment(DependencyObject obj, DataGridEnvironment value) => obj.SetValue(DataGridEnvironmentProperty, value);
private async static void DataGrid_Sorting(object sender, DataGridSortingEventArgs e) { var dataGrid = (DataGrid)sender; IList itemsSource = dataGrid.ItemsSource as IList; if (itemsSource == null) { return; } DataGridEnvironment environment = GetDataGridEnvironment(dataGrid); if (environment == null && itemsSource is INotifyCollectionChanged) { environment = new DataGridEnvironment(dataGrid); var notifyCollectionChanged = (INotifyCollectionChanged)itemsSource; notifyCollectionChanged.CollectionChanged += environment.CollectionChanged_CollectionChanged; SetDataGridEnvironment(dataGrid, environment); } DataGridColumn sortColumn = e.Column; // Check if column has command override for sort. ICommand overrideCommand = GetSortCommandOverride(sortColumn); if (overrideCommand != null) { e.Handled = true; environment?.DisableReset(true); var newSortDirection = sortColumn.SortDirection == System.ComponentModel.ListSortDirection.Ascending ? System.ComponentModel.ListSortDirection.Descending : System.ComponentModel.ListSortDirection.Ascending; var parameter = new SortCommandOverrideParameter(GetSortCommandOverrideParameter(sortColumn), newSortDirection); if (overrideCommand is IAsyncCommand <SortCommandOverrideParameter> ) { await((IAsyncCommand <SortCommandOverrideParameter>)overrideCommand).ExecuteAsync(parameter); } else if (overrideCommand is IAsyncCommand <object> ) { await((IAsyncCommand <object>)overrideCommand).ExecuteAsync(parameter); } else { overrideCommand.Execute(parameter); } sortColumn.SortDirection = newSortDirection; environment?.DisableReset(false); return; } // Normal operation resumed. OperationResult <ComparerFunctions> comparer = GetComparer(dataGrid, sortColumn); if (comparer.WasSuccessful) { e.Handled = true; environment?.DisableReset(true); NormalSort(dataGrid, sortColumn, comparer.Result, itemsSource); environment?.DisableReset(false); return; } }