wpf MVVM:ViewModel 中的 CollectionView 或 xaml 中的 CollectionViewSource?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/979317/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 20:33:21  来源:igfitidea点击:

MVVM: CollectionView in ViewModel or CollectionViewSource in xaml?

wpfcollectionsmvvm

提问by Grokys

I'm developing a WPF application using the MVVM pattern and I need to display a list of items in a ListView (with filtering), with the fields of the selected item displayed in a Master/Detail view. I'm torn between the following two ways of doing this:

我正在使用 MVVM 模式开发 WPF 应用程序,我需要在 ListView(带过滤)中显示项目列表,在主/详细视图中显示所选项目的字段。我在以下两种方法之间左右为难:

  1. Exposing a CollectionView in my ViewModel, and binding to this.
  2. Exposing a plain IList in my ViewModel, and using CollectionViewSource to create the CollectionView in XAML.
  1. 在我的 ViewModel 中公开一个 CollectionView,并绑定到它。
  2. 在我的 ViewModel 中公开一个普通的 IList,并使用 CollectionViewSource 在 XAML 中创建 CollectionView。

Is there an accepted way of doing this? Any thoughts on the best way?

有没有一种可接受的方式来做到这一点?关于最佳方法的任何想法?

采纳答案by Kent Boogaart

I do the former (expose CollectionViewfrom the VM) but what really matters is where your filtering logic is. That should definitely be in the VM so that it can be tested, even if the view has to wire up the CollectionViewSourceto the VM. That said, I don't think there's anything particularly nasty or anti-MVVM about exposing a CollectionView from your VM.

我做前者(CollectionView从 VM暴露),但真正重要的是你的过滤逻辑在哪里。这绝对应该在 VM 中,以便可以对其进行测试,即使视图必须连接CollectionViewSource到 VM。也就是说,我认为从 VM 公开 CollectionView 并没有什么特别讨厌或反 MVVM 的地方。

回答by Robert

I know I'm a bit late answering your question but I just saw it today.

我知道我回答你的问题有点晚了,但我今天才看到。

I have created master/detail viewmodels that use the CollectionViewSource and blogged about it.

我已经创建了使用 CollectionViewSource 的主/细节视图模型,并在博客中介绍了它。

I wrote about a viewmodel for master/detail tables here that uses : http://reyntjes.blogspot.com/2009/04/master-detail-viewmodel_24.html

我在这里写了一个用于主/细节表的视图模型,它使用:http: //reyntjes.blogspot.com/2009/04/master-detail-viewmodel_24.html

You can also find a viewmodel for the observablecollection class on my blog pages.

您还可以在我的博客页面上找到 observablecollection 类的视图模型。

Maybe you find it of use to you.

也许你觉得它对你有用。