Search code examples
datatableitemssourcelistcollectionview

WPF BindingListCollectionView to ListCollectionView for DataTable as ItemsSource


I want to do custom sorting on a ListView which has a DataTable as ItemsSource:

myListView.ItemsSource = (data as DataTable);

And this are the first lines of my sorting function:

DataView view = (myListView.ItemsSource as DataTable).DefaultView;

ListCollectionView coll = (ListCollectionView)CollectionViewSource.GetDefaultView(view);

The second line throws an execption like:

Unable to cast "System.Windows.Data.BindingListCollectionView" to "System.Windows.Data.ListCollectionView"

Has anyone a solution? Thx 4 answers


Solution

  • It returns an ICollectionView that is not a ListCollectionView. You most likely want a view on top of a view to get the features that ListCollectionView has. And since ICollectionView implements CollectionChanged, you wouldn't want to use BindingListCollectionView.

    DataView view = (myListView.ItemsSource as DataTable).DefaultView;
    
    ListCollectionView coll = new ListCollectionView(CollectionViewSource.GetDefaultView(view));
    

    Although an alternative would be:

    DataView view = (myListView.ItemsSource as DataTable).DefaultView;
    
    BindingListCollectionView coll = new BindingListCollectionView(view);
    

    If you only wanted only one view.

    If you are binding directly to a WPF control, it is best to bind directly to it without making a BindingListCollectionView/ListCollectionView, as DefaultView already allows sorting of the DataTable.

    Binding binding = new Binding() { Source = (myListView.ItemsSource as DataTable) };
    
    this.myListView.SetBinding(myListView.ItemsSourceProperty, binding);
    
    DataView view = (myListView.ItemsSource as DataTable).DefaultView;
    
    view.Sort = "Age";
    

    Hopefully Helpful,

    TamusJRoyce