/// <summary> /// Handles the Click event of the ColumnHeader control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.Windows.RoutedEventArgs" /> instance containing the event data.</param> private static void ColumnHeader_Click(object sender, RoutedEventArgs e) { GridViewColumnHeader columnHeader = e.OriginalSource as GridViewColumnHeader; if (columnHeader != null) { ListView listView = sender as ListView; if (listView != null) { string propertyName; // Determine the binding to use for the sorting. Binding binding = columnHeader.Column.DisplayMemberBinding as Binding; if (binding == null || binding.Path == null) { propertyName = GetPropertyName(columnHeader.Column); } else { propertyName = binding.Path.Path; } // Apply the sorting for the given property. if (string.IsNullOrEmpty(propertyName)) { return; } // Determine the direction of the sorting. ListSortDirection direction = GetSortingDirection(columnHeader); // The use of the comparer is much faster than using the sort descriptions. IListViewComparer comparer = GetSortComparer(listView); if (comparer != null) { // Update the properties. comparer.PropertyName = propertyName; comparer.Direction = direction; // Apply the comparison. ListCollectionView collectionView = (ListCollectionView)CollectionViewSource.GetDefaultView(listView.ItemsSource); collectionView.CustomSort = comparer; } else if (!propertyName.Contains(".")) { listView.Items.SortDescriptions.Clear(); listView.Items.SortDescriptions.Add(new SortDescription(propertyName, direction)); } // Update the sort adorner. UpdateAdorner(columnHeader, direction); } } }
/// <summary> /// Sets the sort comparer. /// </summary> /// <param name="o">The o.</param> /// <param name="value">The value.</param> public static void SetSortComparer(DependencyObject o, IListViewComparer value) { o.SetValue(SortComparerProperty, value); }