Reputation: 1526
I have a DataGrid that I'm trying to implement a CustomSort on. The DataGrid ItemsSource always returns with type of EnumerableCollectionView which is unsortable. I'm trying to convert EnumerableCollectionView to ListCollectionView so that I can implement my CustomSort method on it. The underlying collection is an ObservableDictionary. How would one go about converting EnumerableCollectionView to ListCollectionView OR returning ListCollectionView from ItemsSource?
Upvotes: 5
Views: 2443
Reputation: 1
You might have an issue working with a set/subset from a larger collection. For example:
ItemsSource = dsJournals.Local.Where(j => j.Jrnl == "AAA");
dsJournals.Local
is a ListCollectionView
but the result of the LINQ query is a EnumerableCollectionView
.
Upvotes: 0
Reputation: 1526
Ended up solving this one on my own. I created a new List which held all my DataGridRows, then creating a new ListCollectionView based on my List of DataGridRows. I then performed my custom sort based on the new List and setting the DataGrid's ItemsSource to the ListCollectionView.
private void PerformCustomSort(DataGridColumn column) {
ListSortDirection direction = (column.SortDirection != ListSortDirection.Ascending) ? ListSortDirection.Ascending : ListSortDirection.Descending;
column.SortDirection = direction;
List<DataGridRow> dgRows = new List<DataGridRow>();
var itemsSource = dataGrid1.ItemsSource as IEnumerable;
foreach (var item in itemsSource) {
DataGridRow row = dataGrid1.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;
if (null != row) {
dgRows.Add(row);
}
}
ListCollectionView lcv = new ListCollectionView(dgRows);
SortOrders mySort = new SortOrders(direction, column);
lcv.CustomSort = mySort;
dataGrid1.ItemsSource = lcv;
}
This allowed me to avoid the EnumerableCollectionView and allow sorting.
Upvotes: 2
Reputation: 11252
I think you're going about it the wrong way. You don't let the DataGrid determine what kind of collection to use, you create the collection explicitly yourself and bind the DataGrid to it.
You probably shouldn't need to retrieve the collection by casting the ItemsSource, you should have it stored as a property of your ViewModel or alternatively in your code-behind.
If you really need to retrieve the reference from the DataGrid, just cast it like so:
ListCollectionView myList = (ListCollectionView)dataGrid.ItemsSource;
But in most cases if you're doing that you're probably doing something wrong with the structure of your code.
Upvotes: 1