I have following code
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var entities = new DemoEntities();
var depts = entities.Depts.ToList(); // entity framwork dept table
CollectionViewSource cvs = (CollectionViewSource)CollectionViewSource.GetDefaultView(depts);
}
}
My intention is to bind this collection the following windows resource in XAML
<Window.Resources>
<CollectionViewSource x:Key="Departments"/>
</Window.Resources>
Using
CollectionViewSource collectionViewSource = this.FindResource("Departments") as CollectionViewSource;
However while executing following line of code
CollectionViewSource cvs = (CollectionViewSource)CollectionViewSource.GetDefaultView(depts);
it is throwing an exception and that exception's inner exception is following
{"Unable to cast object of type 'System.Windows.Data.ListCollectionView' to type 'System.Windows.Data.CollectionViewSource'."}
Could some one help me on this by providing how to create CollectionViewSource using code behind?
CollectionViewSource.GetDefaultView(depts)
returns an ICollectionView
. CollectionViewSource
is mainly a means to determine what type of ICollectionView
to use depending upon the collection provided.
If you really do want to create a CollectionViewSource
however, you could probably do it like so:
var collectionViewSource = new CollectionViewSource();
collectionViewSource.Source = depts;
I do however believe what you are trying to achieve could be done in a better way. For example:
var collectionViewSource = this.FindResource("Departments") as CollectionViewSource;
collectionViewSource.Source = depts;
The CollectionViewSource.GetDefaultView method returns an ICollectionView
ICollectionView icv = CollectionViewSource.GetDefaultView(dg1.ItemsSource);
But if you are binding to a collection that inherits from IList (which it does in your case), it can also be cast to a more powerful type...
ListCollectionView icv = CollectionViewSource.GetDefaultView(dg1.ItemsSource)
as ListCollectionView;
Which is what the compiler wants to do, but cannot. Hence the error. So change your 'cvs' to be of the appropriate type...
ICollectionView or ListCollectionView... depending upon what you want to do with the result...
NOTE: Bea Stolnitz's seminal blog entry on binding to a CollectionView is at her old blog
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With