我的ViewModel是否应该具有Views或ViewModels的ObservableCollection? [英] Should my ViewModel have an ObservableCollection of Views or ViewModels?

查看:92
本文介绍了我的ViewModel是否应该具有Views或ViewModels的ObservableCollection?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在尝试使用 ItemsControl 时,我试图通过 DataTemplates 绑定到ViewModel上的 ObservableCollections ,来理解MVVM的基本设计方法.

I'm trying to understand the basic MVVM design approach when using ItemsControl by binding it via DataTemplates to ObservableCollections on the ViewModel.

我看过绑定到字符串视图 ViewModels 的ObservableCollections的示例.

I've seen examples that bind to ObservableCollections of strings, Views, and ViewModels.

绑定到字符串似乎仅用于演示,WPF的强大功能是绑定到"包含View集合的ViewModels包含ViewModels集合的视图模型".似乎真的出来了.

Binding to strings seems to be only for demos, it is the binding to "ViewModels that contain collections of Views that contain collections of ViewModels" that the power of WPF seems to really come out.

对于那些精通MVVM模式的用户,将ItemsControl,ListView,ListBox绑定到ViewModel中的集合的标准方法是什么?我正在从这样的经验中寻求建议:

For those of use proficient in the MVVM pattern, what is your standard approach to binding ItemsControl, ListView, ListBox to collections in a ViewModel? I'm looking for advice from experience like this:

  • 始终使用ObservableCollection< ...>,而不使用List< ...>,因为...
  • 比ItemsControl更好的显示集合是...
  • 为了使过滤器可以在ViewModel中工作而不是在代码后方工作,请使用...
  • 在...时使用View的集合,在...时使用ViewModel的集合
  • 我有90%的时间创建了ItemsControl并将其绑定到具有自己的ViewModels的Views的ObservableCollection ...

推荐答案

出于以下原因,我将使用ViewModel的ObservableCollection:

I would use an ObservableCollection of ViewModels for the following reasons:

  • ObservableCollection已经具有可用于发出信号的事件,该事件已被修改(例如,从集合中添加/删除项目时).
  • 我们位于ViewModel的层",因此它提供了更清晰的分隔,以使ViewModel包含ViewModels而不是Views的集合
  • 如果有必要从集合中的项目中修改或获取数据,则可以轻松地修改/访问该数据(如果这些项目是ViewModels的话)(如果它们是视图,则您经常会投射View的DataContext或访问其UI元素).

这篇关于我的ViewModel是否应该具有Views或ViewModels的ObservableCollection?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆