wpf中ListView控件点击列头排序功能实现(超简洁实用)
程序员文章站
2022-07-13 23:10:03
...
.xaml文件中的主要代码
<ListView Name="lvMeasureData" GridViewColumnHeader.Click="Sort_Click"
SelectionChanged="lvMeasureData_SelectionChanged" >
<ListView.View>
<GridView >
<GridViewColumn Header="测量日期" DisplayMemberBinding="{Binding MeasureDate,StringFormat='yyyy/MM/dd HH:mm'}" Width="180"></GridViewColumn>
<GridViewColumn Header="测量名称" DisplayMemberBinding="{Binding MeasureName}" Width="200"></GridViewColumn>
<!--<GridViewColumn Header="组织结构" DisplayMemberBinding="{Binding PersonnelCompany}" Width="100"></GridViewColumn>-->
<GridViewColumn Header="被测人" DisplayMemberBinding="{Binding PersonnelName}" Width="120"></GridViewColumn>
<GridViewColumn Header="测量模式" DisplayMemberBinding="{Binding MeasureModString}" Width="0">
</GridViewColumn>
<GridViewColumn Header="类型" DisplayMemberBinding="{Binding MeasureTypeString}" Width="80"></GridViewColumn>
</GridView>
</ListView.View>
</ListView>
.xmal.cs文件中的排序方法sort()
#region listview 控件点击列头排序方法
//
private ListSortDirection _sortDirection;
private GridViewColumnHeader _sortColumn;
private void Sort_Click(object sender, RoutedEventArgs e)
{
GridViewColumnHeader column = e.OriginalSource as GridViewColumnHeader;
if (column == null||column.Column==null)
{
return;
}
if (_sortColumn == column)
{
// Toggle sorting direction
_sortDirection = _sortDirection == ListSortDirection.Ascending ?
ListSortDirection.Descending :
ListSortDirection.Ascending;
}
else
{
// Remove arrow from previously sorted header
if (_sortColumn != null&& _sortColumn.Column!=null)
{
_sortColumn.Column.HeaderTemplate = null;
_sortColumn.Column.Width = _sortColumn.ActualWidth - 20;
}
_sortColumn = column;
_sortDirection = ListSortDirection.Ascending;
column.Column.Width = column.ActualWidth + 20;
}
if (_sortDirection == ListSortDirection.Ascending)
{
column.Column.HeaderTemplate = Resources["ArrowUp"] as DataTemplate;
}
else
{
column.Column.HeaderTemplate = Resources["ArrowDown"] as DataTemplate;
}
string header = string.Empty;
// if binding is used and property name doesn't match header content
Binding b = _sortColumn.Column.DisplayMemberBinding as Binding;
if (b != null)
{
header = b.Path.Path;
}
ICollectionView resultDataView = CollectionViewSource.GetDefaultView(
(sender as ListView).ItemsSource);
resultDataView.SortDescriptions.Clear();
resultDataView.SortDescriptions.Add(
new SortDescription(header, _sortDirection));
}
#endregion
运行程序,点击列头发现已实现排序功能,O(∩_∩)O哈哈~欢迎提问和指正