我在为ListView订购数据时遇到问题。我有EventDisplay类,它是ListView的ObservableCollection(称为事件)
private ObservableCollection<EventDisplay> currentEvents = new ObservableCollection<EventDisplay>();
private void Events_Loaded(object sender, RoutedEventArgs e)
{
sv = (ScrollViewer)VisualTreeHelper.GetChild(VisualTreeHelper.GetChild(this.Events, 0), 0);
Events.ItemsSource = currentEvents;
}
然后我按功能添加新数据:
private void LoadDataToList(List<EventDisplay> newItems)
{
foreach (EventDisplay ed in newItems)
{
//Set some additional data
currentEvents.Add(ed);
}
//When this line below is commented ListView data is updated
//but is not sorted, when i uncomment the listview data is not being updated
//currentEvents = new ObservableCollection<EventDisplay>(currentEvents.OrderByDescending(x => x.ed.date).ToList());
}
那么在Windows 8.1应用程序中为ListView排序数据的正确方法是什么?
答案 0 :(得分:1)
您应该执行以下操作:
currentEvents = new ObservableCollection<EventDisplay>(currentEvents.OrderByDescending(x => x.ed.date).ToList());
Events.ItemsSource = currentEvents;
这会强制ListView重新绑定到新的已排序的可观察集合。
另一种选择是对Observable集合进行排序。但是,它可能会引入闪烁,因为ListView会随着排序的进行而不断更新。
如果您不希望ScrollView重置其位置,可以保存滚动视图位置,然后在对列表进行排序后将其恢复。 我已经成功实现了一个支持排序的自定义ObservableCollection,但是通过在排序期间挂起更改通知然后发出重置通知来防止UI闪烁。即使遇到重置事件,ScrollView也应保持在当前位置。
答案 1 :(得分:1)
将此用于添加商品代码:
foreach (EventDisplay ed in newItems.OrderByDescending(x => x.ed.date).ToList()
{
//Set some additional data
currentEvents.Add(ed);
}
您无法工作的原因是您重新分配了currentEvents
引用,而不是更新ObservableCollection
。
答案 2 :(得分:1)
你可以排序&amp;过滤ObservableCollection的视图(解释here)
public class ViewableCollection<T> : ObservableCollection<T>
{
private ListCollectionView _View;
public ListCollectionView View
{
get
{
if (_View == null)
{
_View = new ListCollectionView(this);
}
return _View;
}
}
}
示例的数据结构:
interface ICustomer
{
string CuctomerName{get;set;}
int Age{get;set;}
}
代码使用示例:
ViewableCollection<ICustomer> vCustomers = new ViewableCollection<ICustomer>();
// Sorting settings:
ViewableCollection<ICustomer> vCustomers.View.SortDescriptions.Add(new SortDescription("CustomerName", ListSortDirection.Ascending));
vCustomers.View.Filter = MyCustomFilterMethod;
// add data to collection
MyCustomers.ToList().ForEach(customer => vCustomers.Add(customer));
Examlpe过滤方法:
private bool MyCustomFilterMethod(object item)
{
ICustomer customer = item as ICustomer;
return customer.Age > 25;
}
当您需要刷新过滤器时,您唯一需要做的就是调用:
this.vCustomers.View.Refresh();
然后将GUI绑定到vCustomers.View
您无需重置绑定源等。