ceth
ceth

Reputation: 45325

Sorting data in ListView

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 ?

Upvotes: 0

Views: 495

Answers (1)

har07
har07

Reputation: 89325

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);

Upvotes: 1

Related Questions