作者:mobiledu2502879663 | 来源:互联网 | 2023-09-17 10:54
要实现ListView点击某一列进行排序,需要处理列点击事件
下面的代码支持ListView 多个列点击排序,并会记住点击过的每个列的排序方向 。
private void GridViewColumnHeader_Click(object sender, RoutedEventArgs e) {ListView view = sender as ListView;if (view == null) {return;}if (e.OriginalSource is GridViewColumnHeader) {//获取点击列GridViewColumn clickedColumn = (e.OriginalSource as GridViewColumnHeader)?.Column;if (clickedColumn != null) {//获取该列绑定的属性string bindingProperty = (clickedColumn.DisplayMemberBinding as Binding)?.Path.Path;if (bindingProperty == null) {return;}SortDescriptionCollection sdc = view.Items.SortDescriptions;ListSortDirection sortDirection = ListSortDirection.Ascending;foreach (var sd in sdc) {if (sd.PropertyName.Equals(bindingProperty)) {//改变排序方向sortDirection = (ListSortDirection) ((((int) sd.Direction) + 1) % 2);//取得排序方向后,删除当前的SortDescriptionsdc.Remove(sd);break;}}//添加新的SortDescription到SortDescriptions首位,使之生效sdc.Insert(0,new SortDescription(bindingProperty, sortDirection));}}}
排序是根据列的类型来的,就ID列来说,int类型的排序结果是2,3,17,而如果你把该列
类型改为string,结果就会是17,2,3,如果你定义列的时候不加类型,默认是string,如
果是自定义类型,那么请继承IComparable接口,实现CompareTo方法。