Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create collection view source in code behind for wpf app

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?

like image 504
manu Avatar asked Dec 13 '22 06:12

manu


2 Answers

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;
like image 188
Lukazoid Avatar answered Jan 19 '23 11:01

Lukazoid


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

like image 37
Gayot Fow Avatar answered Jan 19 '23 09:01

Gayot Fow