在ListView的数据排序 [英] Sorting data in ListView
问题描述
我有一个ListView在我的XAML:
I have a ListView in my XAML:
<ListView Margin="10" Name="lvDataBinding"></ListView>
在code我有用户等级:
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";
}
}
和code结合用户的集合的ListView:
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;
现在我想通过User.Name或User.Age ListView中的数据进行排序。我该怎么办呢?
Now I want to sort the data in ListView by User.Name or User.Age. How can I do it ?
推荐答案
您可以通过添加 SortDescription
对象尝试<一个href=\"http://msdn.microsoft.com/en-us/library/system.windows.data.collectionview.sortdescriptions%28v=vs.110%29.aspx\"相对=nofollow> CollectionView.SortDescriptions
财产。例如通过在的ListView
数据排序 User.Age
:
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));
我正要使用建议 CollectionView.SortDescriptions
意识到<前一href=\"http://stackoverflow.com/questions/14956999/filtering-and-sorting-of-an-observablecollection-in-listview-binding\">it在WinRT的是不支持的。可能的解决方法是通过重新分配的ItemsSource
新的有序集合。例如,通过排序 User.Age
:
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);
这篇关于在ListView的数据排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!