您可以幫我使用PagedCollectionview將自定義排序映射到observablecollection.Below是排序部分工作正常的代碼,但它不會刷新網格作爲從第一列未清除PagedCollectionview&Silverlight中的自定義排序
例如,如果我使用「描述」對它進行排序,它可以在兩個方向上工作(asc & desc)。但是,如果我點擊「類型」標題,使用「描述」對集合進行排序後,應該使用「類型」清除較早的排序& 「僅列。
private void SortCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.Action == NotifyCollectionChangedAction.Remove || e.Action == NotifyCollectionChangedAction.Reset)
return;
if (e.Action == NotifyCollectionChangedAction.Replace || e.Action == NotifyCollectionChangedAction.Add)
{
MyPVC.SortDescriptions.Clear();
if (e.NewItems.Count > 0)
{
MyPVC.SortDescriptions.Clear();
SortDescription sd = (SortDescription) e.NewItems[0];
if (sd.PropertyName == "description")
{
e.NewItems.Clear();
using (MyPVC.DeferRefresh())
{
ObservableCollection<MyClass> source = ((ObservableCollection<MyClass>)MyPVC.SourceCollection);
if (source == null)
return;
bool asc = (sd.Direction == ListSortDirection.Ascending);
var source1 = new List<MyClass>(source);
source1.Sort((a, b) =>
{
int left = 0;
int right = 0;
var ret = 0;
if (int.TryParse(a.description, out left) && int.TryParse(b.description, out right))
{
ret = (left < right) ? -1 : (left == right) ? 0 : 1;
if (!asc)
ret = -ret;
}
return ret;
});
var newsource = new ObservableCollection<MyClass>(source1);
MyPVC = new PagedCollectionView(newsource);
((INotifyCollectionChanged)MyPVC.SortDescriptions).CollectionChanged += SortCollectionChanged;
MyPVC.SortDescriptions.Clear();
}
MyClassDataGrid.ItemsSource = MyPVC;
MyPVC.Refresh();
}
if (sd.PropertyName == "Type")
{
MyPVC.SortDescriptions.Clear();
//MyPVC = new PagedCollectionView(MyPVC);
e.NewItems.Clear();
using (MyPVC.DeferRefresh())
{
ObservableCollection<MyClass> source = ((ObservableCollection<MyClass>)MyPVC.SourceCollection);
if (source == null)
return;
bool asc = (sd.Direction == ListSortDirection.Ascending);
var source1 = new List<MyClass>(source);
source1.Sort((a, b) =>
{
int left = 0;
int right = 0;
var ret = 0;
if (int.TryParse(a.Type, out left) && int.TryParse(b.Type, out right))
{
ret = (left < right) ? -1 : (left == right) ? 0 : 1;
if (!asc)
ret = -ret;
}
return ret;
});
var newsource = new ObservableCollection<MyClass>(source1);
MyPVC = new PagedCollectionView(newsource);
((INotifyCollectionChanged)MyPVC.SortDescriptions).CollectionChanged += SortCollectionChanged;
MyPVC.SortDescriptions.Clear();
}
}
}
}
}
private void MyClasstableView_ColumnHeaderClick(object sender, ColumnHeaderClickEventArgs e)
{
((INotifyCollectionChanged) MyPVC.SortDescriptions).CollectionChanged += SortCollectionChanged;
}
你得到的錯誤是什麼?你能否展示數據的類?這將非常有幫助。 – Danexxtone
thanx丹麥爲你的時間我有一個解決這個問題的方法。我在其他領域的基礎上排序收集 – xoanon