Sorting data in ListView

送分小仙女□ 提交于 2019-12-12 02:58:28

问题


I have a ListView in my XAML:

<ListView Margin="10" Name="lvDataBinding"></ListView>

In the code I have User class:

public class User
{
    public string Name { get; set; }
    public int Age { get; set; }

    public override string ToString
    {
        return this.Name + ", " + this.Age + " years old";
    }
}

and code that binds the collection of Users to ListView:

List<User> items = new List<User>();
items.Add(new User() { Name = "John Doe", Age = 42 });
items.Add(new User() { Name = "Jane Doe", Age = 39 });
items.Add(new User() { Name = "Sammy Doe", Age = 13 });
items.Add(new User() { Name = "Any Dam", Age = 90 });
lvDataBinding.ItemsSource = items;

Now I want to sort the data in ListView by User.Name or User.Age. How can I do it ?


回答1:


You can try by adding a SortDescription object to the CollectionView.SortDescriptions property. For example to sort data in the ListView by User.Age :

CollectionView view = 
    (CollectionView)CollectionViewSource.GetDefaultView(lvDataBinding.ItemsSource);
view.SortDescriptions.Add(new SortDescription("Age", ListSortDirection.Ascending));

I was about to suggest using CollectionView.SortDescriptions before realizing that it isn't supported in WinRT. Possible workaround is by reassigning ItemsSource to the new ordered collection. For example to sort by User.Age :

var source = (List<User>)lvDataBinding.ItemsSource;
lvDataBinding.ItemsSource = source.OrderBy(o => o.Age);


来源:https://stackoverflow.com/questions/25862244/sorting-data-in-listview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!