我正在尝试通过将 DataTemplates 绑定到ViewModel上的 DataTemplates 来使用 ItemsControl 来理解基本的MVVM设计方法 .
我见过绑定到 strings , Views 和 ViewModels 的ObservableCollections的示例 .
绑定到字符串似乎仅适用于 demos ,它是绑定到“ ViewModels that contain collections of Views that contain collections of ViewModels ”WPF的强大功能似乎真的出来了 .
For those of use proficient in the MVVM pattern, what is your standard approach to binding ItemsControl, ListView, ListBox to collections in a ViewModel? 我正在寻找以下经验的建议:
-
始终使用ObservableCollection <...>并且永远不会列出<...>因为......
_999_比ItemsControl更好的东西显示集合是... -
为了使过滤能够在ViewModel中工作而不是代码隐藏,请使用...
-
使用View的集合......和ViewModels的集合时......
-
90%的时间我创建ItemsControl并将其绑定到具有自己的ViewModel的ObservableCollection视图...
3 回答
我会使用ViewModel的ObservableCollection,原因如下:
ObservableCollection已经具有可用于在其被修改时发信号的事件(例如,当从集合中添加/移除项目时) .
我们're at the ViewModel ' layer'因此它提供了更清晰的分离,使ViewModel包含ViewModel而不是Views的集合
如果需要修改或从集合中的项目获取数据,如果项目是ViewModel(如果他们经常投射View的DataContext或访问其UI元素),则可以更轻松地修改/访问该数据 .
我喜欢使用ViewModels的ObservableCollection . 绑定到集合的视图可以定义一个DataTemplate,为ViewModel提供外观 . 这导致组件之间的耦合较少 .
我有同样的问题,但用“模型”替换“视图” . :)
我有一个MODEL与其他模型的集合 . 我希望我的viewmodel有一个可观察的其他视图模型集合,但是一旦我像这样实例化它 - 模型集合内容之间的连接就会丢失 . 我现在需要开始将viewmodels observable集合中的所有事件连接回模型集合吗?