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

WPF中ListView排序

程序员文章站 2022-03-07 14:21:06
...
<!--xaml-->

 <ListView Margin="51,54,70,64" x:Name="lvList" GridViewColumnHeader.Click="lvList_Click_1" ItemsSource="{Binding}"  >
            <ListView.View>
                <GridView >
                    <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}" Width="50"></GridViewColumn>
                    <GridViewColumn Header="Age" DisplayMemberBinding="{Binding Age}" Width="50"></GridViewColumn>
                    <GridViewColumn Header="Email" DisplayMemberBinding="{Binding Email}" Width="50"></GridViewColumn>
                </GridView>
            </ListView.View>
        </ListView>

//后台代码
        private void lvList_Click_1(object sender, RoutedEventArgs e)
        {
            if (e.OriginalSource is GridViewColumnHeader)
            {
                //获得点击的列
                GridViewColumn clickedColumn = (e.OriginalSource as GridViewColumnHeader).Column;
                if (clickedColumn != null)
            
                {
                    //Get binding property of clicked column
                  
                    string bindingProperty = (clickedColumn.DisplayMemberBinding as Binding).Path.Path;
                    //获得listview项是如何排序的
                    SortDescriptionCollection sdc = this.lvList.Items.SortDescriptions;

                    //按升序进行排序
                    ListSortDirection sortDirection = ListSortDirection.Ascending;
                    if (sdc.Count > 0)
                    {
                        SortDescription sd = sdc[0];
                        sortDirection = (ListSortDirection)((((int)sd.Direction) + 1) % 2);
                        sdc.Clear();
                    }
                    sdc.Add(new SortDescription(bindingProperty, sortDirection));
                }
            }

        }