WPF BindingListCollectionView to ListCollectionView for DataTable as ItemsSource

你离开我真会死。 提交于 2020-01-24 21:00:07

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/2890371/wpf-bindinglistcollectionview-to-listcollectionview-for-datatable-as-itemssource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!