using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; using System.Windows.Controls; using System.Windows; using System.Windows.Data; namespace HemsClient { public class SortableListView : ListView { //最后单击的标题 private GridViewColumnHeader _lastHeaderClicked = null; //默认升序 private ListSortDirection _lastDirection = ListSortDirection.Ascending; //排序字段的附加属性 public static readonly DependencyProperty SortPropertyNameProperty = DependencyProperty.RegisterAttached("SortPropertyName", typeof(string), typeof(SortableListView)); // 附加属性的Get方法 public static string GetSortPropertyName(GridViewColumn obj) { return (string)obj.GetValue(SortPropertyNameProperty); } //附加属性的Set方法 public static void SetSortPropertyName(GridViewColumn obj, string value) { obj.SetValue(SortPropertyNameProperty, value); } public SortableListView() { //注册单击标题事件 this.AddHandler( GridViewColumnHeader.ClickEvent, new RoutedEventHandler(GridViewColumnHeaderClickedHandler)); } /// <summary> /// 排序方法 /// </summary> /// <param name="sortBy">排序字段</param> /// <param name="direction">升序/降序</param> private void Sort(string sortBy, ListSortDirection direction) { ICollectionView dataView = CollectionViewSource.GetDefaultView(this.ItemsSource); if (dataView != null) { dataView.SortDescriptions.Clear(); SortDescription sd = new SortDescription(sortBy, direction); dataView.SortDescriptions.Add(sd); dataView.Refresh(); } } //单击标题调用的方法 private void GridViewColumnHeaderClickedHandler(object sender, RoutedEventArgs e) { GridViewColumnHeader headerClicked = e.OriginalSource as GridViewColumnHeader; ListSortDirection direction; if (headerClicked != null && headerClicked.Role != GridViewColumnHeaderRole.Padding) { if (headerClicked != _lastHeaderClicked) { direction = ListSortDirection.Ascending; } else { if (_lastDirection == ListSortDirection.Ascending) { direction = ListSortDirection.Descending; } else { direction = ListSortDirection.Ascending; } } //获得排序字段 string sortBy = SortableListView.GetSortPropertyName(headerClicked.Column); if (string.IsNullOrEmpty(sortBy)) { sortBy = headerClicked.Column.Header as string; return; } //排序操作 this.Sort(sortBy, direction); _lastHeaderClicked = headerClicked; _lastDirection = direction; } } } }
转载于:https://www.cnblogs.com/qiups/p/8682972.html