MVVM 中的 ViewModel 应该引用视图吗? [英] Should a ViewModel in MVVM reference the View?

查看:16
本文介绍了MVVM 中的 ViewModel 应该引用视图吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 MVVM (Model-View-ViewModel) 模式中,ViewModel 应该引用视图.我认为不应该.但是下面的场景应该如何处理呢?我有一个视图,它有一个选项卡控件作为主容器,这个视图的视图模型实现了一个命令来向选项卡控件添加一个新选项卡.简单的方法是允许视图模型引用视图,然后在命令实现中以编程方式将新选项卡添加到视图中的选项卡控件.这似乎是错误的.我应该以某种方式将 tabcontrol 绑定到 viewmodel,然后实现一个数据/控件模板来添加新选项卡.我希望这对某人有意义:)

In the MVVM (Model-View-ViewModel) pattern should the ViewModel reference the view. I would think that it should not. But how should the following scenario be handeled? I have a view that has a tab control as the main container, the viewmodel for this view implements a command to add a new tab to the tab control. The easy way would be to allow the viewmodel to reference the view and then in the command implementation to just programmatically add the new tab to the tabcontrol in the view. This just seems wrong. Should I somehow bind the tabcontrol to the viewmodel and then implement a data/control-template to add the new tabs. I hope this makes some kind of sense to somebody :)

推荐答案

Reed 和 Dan 介绍了一般方法,但参考您的具体情况,TabControl 是一个 ItemsControl,因此可以将其 ItemsSource 绑定到您的 ViewModel 中表示的数据集合要显示的选项卡集.然后,每种类型的选项卡的 UI 可以由特定于项目数据类型的 DataTemplate 表示(使用 DataType 或 DataTemplateSelector).然后,您可以根据需要在 VM 中添加或删除数据项,并使选项卡自动更新,而 VM 无需了解有关 TabControl 的任何信息.

Reed and Dan covered the general approach but in reference to your specific case, TabControl is an ItemsControl and so can bind its ItemsSource to a data collection in your ViewModel representing the set of tabs to display. The UI for each type of tab can then be represented by a DataTemplate specific to the data type of an item (either using DataType or a DataTemplateSelector). You can then add or remove data items as needed from your VM and have the tabs update automatically without the VM knowing anything about the TabControl.

这篇关于MVVM 中的 ViewModel 应该引用视图吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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