欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

WPF中ListView排序实现

程序员文章站 2022-07-13 23:06:45
...

要实现ListView点击某一列进行排序,需要处理列点击事件 

<Window x:Class="ListViewSort.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="300" Width="300" Loaded="Window_Loaded">
    <Grid>
        <ListView GridViewColumnHeader.Click="GridViewColumnHeader_Click" Margin="2" ItemsSource="{Binding Path=DataList}" >
            <ListView.View>
                <GridView>
                    <GridViewColumn  Header="ID" DisplayMemberBinding="{Binding ID}" />
                    <GridViewColumn  Header="Name" DisplayMemberBinding="{Binding Name}" />
                </GridView>
            </ListView.View>
        </ListView>
    </Grid>
</Window>

下面的代码支持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);
                            //取得排序方向后,删除当前的SortDescription
                            sdc.Remove(sd);
                            break;
                        }
                    }
                    //添加新的SortDescription到SortDescriptions首位,使之生效
                    sdc.Insert(0,new SortDescription(bindingProperty, sortDirection));
                }
            }
        }

排序是根据列的类型来的,就ID列来说,int类型的排序结果是2,3,17,而如果你把该列
类型改为string,结果就会是17,2,3,如果你定义列的时候不加类型,默认是string,如
果是自定义类型,那么请继承IComparable接口,实现CompareTo方法。  

相关标签: C# c# wpf