我有一个绑定到ObservableCollection的ListView(作为ItemsSource)。它基本上是按字母顺序排列的字符串名称列表。
我想知道如何将单个项目(字符串)插入到集合中并自动排序,而不必使用整个列表。
另外,有没有办法在执行这样的任务时保持当前的ListViewItem?感谢。
答案 0 :(得分:2)
AdvancedCollectionView是一个集合视图实现 支持过滤,排序和增量加载。它的意思是 用于viewmodel。
using Microsoft.Toolkit.Uwp.UI;
// Grab a sample type
public class Person
{
public string Name { get; set; }
}
// Set up the original list with a few sample items
var oc = new ObservableCollection<Person>
{
new Person { Name = "Staff" },
new Person { Name = "42" },
new Person { Name = "Swan" },
new Person { Name = "Orchid" },
...
};
// Set up the AdvancedCollectionView with live shaping enabled to filter and sort the original list
var acv = new AdvancedCollectionView(oc, true);
// Let's filter out the integers
int nul;
acv.Filter = x => !int.TryParse(((Person)x).Name, out nul);
// And sort ascending by the property "Name"
acv.SortDescriptions.Add(new SortDescription("Name", SortDirection.Ascending));
// Let's add a Person to the observable collection
var person = new Person { Name = "Aardvark" };
oc.Add(person);
// Our added person is now at the top of the list, but if we rename this person, we can trigger a re-sort
person.Name = "Zaphod"; // Now a re-sort is triggered and person will be last in the list
// AdvancedCollectionView can be bound to anything that uses collections.
YourListView.ItemsSource = acv;