gpt4 book ai didi

c# - ICollectionView 接口(interface)类型的变量

转载 作者:行者123 更新时间:2023-12-02 04:52:37 25 4
gpt4 key购买 nike

我是WPF的新手,看起来我也不完全理解C#。
下面的代码应该向 DataGrid 提供排序后的数据。

这是我难以理解的代码:

ObservableCollection<Person> PersonsCollection = new ObservableCollection<Person>();
//this one is easy: I create new collection for objects of class Person and I call it PersonsCollection

ICollectionView PersonsView = CollectionViewSource.GetDefaultView(PersonsCollection);
//this one is more complicated. Does it mean that I create new object called PersonsView which I assume that implements ICollectionView interface?

ListCollectionView personsView = PersonsView as ListCollectionView;
//this one I do not understand. Why do we need it? How can we treat PersonsView as ListCollectionView?

personsView.CustomSort = new PersonSorter();
//here we assign object of PersonSorter class to do the sorting. Fine with me.

dataGrid1.ItemsSource = personsView;
//and here we assign personsView as a ItemsSource for our DataGrid. Fine with me.

有什么帮助吗?谢谢:-)

最佳答案

this one is easy: I create new collection for objects of class Person and I call it PersonsCollection.

正确,但我想先弄清楚一些事情。您可以在此处使用任何集合,或者更准确地说是任何 IEnumberable

ObservableCollection 与普通 IEnumerable 的区别在于,前者会在集合中添加、删除或重新排序项目时发出通知,而后者则不会。

重要:需要注意的一件事是,无论是什么类型的集合,无论是 IEnumberable 还是 ObservableCollection,当该集合是在绑定(bind)中使用,然后 WPF 系统围绕该集合创建一个包装器(source),有点像默认的 View

该 View 实现了 ICollectionView。它保留当前项目的概念并提供排序、导航、过滤和分组等功能。

此 View 与集合相关 (source) 因此,如果您对同一个集合有多个绑定(bind),那么所有这些绑定(bind)实际上都绑定(bind)到 WPF 系统创建的默认 View ,因此它们会被更新当默认 View 更新时一起。

我必须清除最后一个重要主题,因为它与前面的问题有关。

this one is more complicated. Does it mean that I create new object called PersonsView which I assume that implements ICollectionView interface ?

不,或者至少不完全正确。您将获得对 WPF 系统将创建的默认 View 的引用,这就是为什么获取该对象的方法称为 GetDefaultView() 而不是 CreateDefaultView().

this one I do not understand. Why do we need it? How can we treat PersonsView as ListCollectionView?

我们真的不需要它,我们可以不用这条线。我们可以将 PersonView 视为 ListCollectionView 因为

all collections have a default CollectionView. For all collections implementing IList, the ListCollectionView object is the default view object.

MSDN Documentation .

剩下的你没问题,我也没问题,所以不需要评论。

关于c# - ICollectionView 接口(interface)类型的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18552860/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com