【发布时间】:2016-10-31 14:09:44
【问题描述】:
我有一个使用实体框架查询数据库并将结果放在ICollectionView 中的方法。 ICollectionView 充当ItemsSource 的DataGrid。第一次查询时一切正常,但第二次查询时,尽管应用了正确的SortDescriptions,但数据没有正确排序。
这是我尝试查询和分组/排序数据的代码:
CollectionViewSource cvsRS;
private ObservableCollection<productorder> rs;
public ObservableCollection<productorder> RS
{
get { return rs; }
set
{
if (rs != value)
{
rs = value;
OnPropertyChanged("RS");
}
}
}
private ICollectionView rsView;
public ICollectionView RSView
{
get { return rsView; }
set
{
if (rsView != value)
{
rsView = value;
OnPropertyChanged("RSView");
}
}
}
public void QueryDatabase()
{
RS = new ObservableCollection<productorder>(DatabaseEntities.productorders.Where(o => o.month.id == CurrentMonth.id));
if (RS != null)
{
cvsRS.Source = RS;
RSView = cvsRS.View;
RSView.GroupDescriptions.Clear();
RSView.GroupDescriptions.Add(new PropertyGroupDescription("producttype.productcategory.name"));
RSView.GroupDescriptions.Add(new PropertyGroupDescription("producttype.name"));
RSView.SortDescriptions.Clear();
RSView.SortDescriptions.Add(new SortDescription("producttype.productcategory.sortorder", ListSortDirection.Ascending));
RSView.SortDescriptions.Add(new SortDescription("client.name", ListSortDirection.Ascending));
RSView.Refresh();
CurrentRecord = null;
SelectedRecords = null;
}
}
分组工作正常,但根据排序,分组的顺序不正确。我尝试了许多可能的“修复”但没有成功(例如,将排序/组描述直接添加到CollectionViewSource,在分组之前排序,删除一些排序/分组,删除SortDescriptions 每个CollectionViewSource does not re-sort on property change) .
有没有人知道如何维护排序顺序而不管执行了多少查询?如果可行的话,我愿意接受在DataGrid 中显示数据的其他查询方法。
【问题讨论】:
-
我会尝试将 Source 绑定一次(不是分配,绑定,使用
Binding类的实例)到一个ObservableCollection<T>属性,当你给它一个新的时它会引发PropertyChanged收藏。然后通过更改属性重新填充。要么折腾一个新的集合,要么清除并重新填充旧的集合。但千万不要碰cvsRS.Source,除非最初设置Binding。 -
希望我正确地解释了这一点,我在构造函数中这样做了:
cvsRS = new CollectionViewSource(); cvsRS.Source = new Binding("RS"); RSView = cvsRS.View;但我收到一个错误:'System.Windows.Data.Binding' 不是属性'Source' 的有效值。 -
我做了一个快速测试,它按预期工作,所以我发布了一个答案,其中包含如何进行绑定的示例。无论如何,将其粘贴到评论中是不可读的。
标签: c# wpf entity-framework sorting icollectionview