本文介绍了如何在WPF应用程序背后的代码中创建集合视图源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码

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);
        }
    }

我的意图是将此集合绑定到XAML中的以下Windows资源

My intention is to bind this collection the following windows resource in XAML

<Window.Resources>
        <CollectionViewSource x:Key="Departments"/>
    </Window.Resources>

使用

CollectionViewSource collectionViewSource = this.FindResource("Departments") as CollectionViewSource;

但是在执行以下代码行时

However while executing following line of code

CollectionViewSource cvs =(CollectionViewSource)CollectionViewSource.GetDefaultView(depts);

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'."}

有人可以通过提供使用后面的代码创建CollectionViewSource的方法来帮助我吗?

Could some one help me on this by providing how to create CollectionViewSource using code behind?

推荐答案

CollectionViewSource.GetDefaultView(depts)返回ICollectionView. CollectionViewSource主要是一种根据提供的集合确定使用哪种类型的ICollectionView的方法.

CollectionViewSource.GetDefaultView(depts) returns an ICollectionView. CollectionViewSource is mainly a means to determine what type of ICollectionView to use depending upon the collection provided.

但是,如果您确实想创建一个CollectionViewSource,则可以这样做:

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;

这篇关于如何在WPF应用程序背后的代码中创建集合视图源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 12:55