【问题标题】:Sorting data in ListView在 ListView 中对数据进行排序
【发布时间】:2014-11-09 19:37:32
【问题描述】:

我的 XAML 中有一个 ListView:

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

在代码中我有用户类:

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

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

以及将用户集合绑定到 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 中的数据进行排序。我该怎么做?

【问题讨论】:

    标签: c# xaml listview windows-8 windows-8.1


    【解决方案1】:

    您可以尝试将SortDescription 对象添加到CollectionView.SortDescriptions 属性。例如将ListView 中的数据按User.Age 排序:

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

    我正要建议使用CollectionView.SortDescriptions,然后才意识到it isn't supported in WinRT。可能的解决方法是将ItemsSource 重新分配给新的有序集合。例如按User.Age 排序:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-03
      • 1970-01-01
      相关资源
      最近更新 更多