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

20,763

Solution 1

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;

Solution 2

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

Share:
20,763
manu
Author by

manu

Updated on July 17, 2022

Comments

  • manu
    manu almost 2 years

    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?

  • manu
    manu over 12 years
    Hi @Garry, once ListCollectionView is created how do we assign it back to the windows resource because the type of that resource is CollectionViewSource