MVVM中的ViewModel应该如何引用View? [英] Should a ViewModel in MVVM reference the View?

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

问题描述

如果ViewModel引用视图,则在MVVM(Model-View-ViewModel)模式中。我会认为它不应该。但是应该如何处理以下情况?我有一个视图具有一个选项卡控件作为主容器,该视图的viewmodel实现了一个命令来添加一个新的选项卡到选项卡控件。简单的方法是允许viewmodel引用视图,然后在命令实现中以编程方式将新选项卡添加到视图中的tabcontrol。这只是似乎错了。我应该以某种方式将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中的数据集合,表示要显示的选项卡集。然后,可以使用特定于项目的数据类型(使用DataType或DataTemplateSelector)的DataTemplate来表示每种类型的选项卡的UI。然后,您可以根据需要从虚拟机添加或删除数据项,并自动更新选项卡,而无需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应该如何引用View?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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