2016-09-29 24 views
0

我有一個名爲「Items」的基礎ObservableCollection,它可以通過它的抽象父對象擁有兩種類型的實例(peopleVM,messageVM)。如何爲每種類型應用不同的排序說明?具有更多數據類型的CollectionView排序集合

這是我的CollectionViewSource:

var cvs = CollectionViewSource.GetDefaultView(Items); 

PropertyGroupDescription groupDescriptionMessages = new PropertyGroupDescription(nameof(ISearchedItem.ItemType)); // Group by item type - peoples | messages 
cvs.GroupDescriptions.Add(groupDescriptionMessages); 

cvs.SortDescriptions.Add(new SortDescription(nameof(ISearchedItem.ItemType), ListSortDirection.Descending)); // Primary sort by Item type - peoples | messages 
cvs.SortDescriptions.Add(new SortDescription(nameof(PeopleVM.ContactName), ListSortDirection.Ascending)); // Sort peoples by name 
cvs.SortDescriptions.Add(new SortDescription(nameof(MessageVM.DateTime), ListSortDirection.Descending)); // Sort messages by date time 

它產生的情侶BindingExpression在VS的輸出,因爲PeopleVM沒有財產的DateTime等等...

我需要這樣的:

--header peoples- //按名稱升序
人1
人2

--header messages-- //按消息日期排序
消息1
消息2
消息3

+0

你是說集合將同時包含這兩種類型的實例,或者有時它是全部的,有時是所有其他的? –

+0

是的,兩種類型一起,具有不同的DataTemplates ...這是如何解決我所知道的這個問題的唯一方法。 –

+1

正確的是,不同的DataTemplates是正確的。但是你不能爲每種類型提供不同的排序描述。一種選擇是使用這兩個類的屬性的聯合集編寫一個接口,並讓它們都實現它。每個類都會爲不支持的屬性返回常量 - 比如messageVM中有一個date屬性,而不是在peopleVM中;如果用戶按日期排序,peopleVM會返回'DateTime.MaxValue'來將它們放在排序順序的末尾。 –

回答

0

我已經結束了使用標準SortDescription:

cvs.SortDescriptions.Add(new SortDescription(nameof(ISearchedItem.ContactName), ListSortDirection.Ascending)); // Sort peoples by name 
cvs.SortDescriptions.Add(new SortDescription(nameof(ISearchedItem.DateTime), ListSortDirection.Descending)); // Sort messages by date time 

這意味着我只需要將getter屬性添加到僅用於排序目的的ISearchedItem的實現中,這些屬性將返回null | DateTime.MaxValue來擺脫BindingExpression錯誤,對我來說看起來很醜,但還沒有找到更好的解決方案。