在 ViewModel 之间共享状态 [英] Sharing state between ViewModels

查看:66
本文介绍了在 ViewModel 之间共享状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个 ViewModel 将相同的模型呈现给不同的视图.一个将模型显示为 ListBox 中的一个项目,另一个将它显示为 TabControl 中的一个选项卡.TabControl是为ListBox中选中的item显示tabs,这样tabs随着选择的变化来来去去.

I have two ViewModels that present the same Model to different Views. One presents the model as an item in a ListBox, the other presents it as a tab in a TabControl. The TabControl is to display tabs for the items that are selected in the ListBox, so that the tabs come and go as the selection changes.

通过向模型添加 IsSelected 属性并将 ViewModel 绑定到它,我可以轻松地同步两个控件(有点像 this),但这会使模型混乱,其中包含不属于其中的演示细节.

I can easily synchronise the two controls by adding an IsSelected property to the Model and binding the ViewModels to it (a bit like this), but this will clutter the Model with presentation details that don't really belong there.

似乎我需要 Model 和 ViewModel 之间的一些东西来保持这个额外的状态.是否有任何模式或示例可以很好地做到这一点?

It seems like I need something between the Model and ViewModels to hold this extra state. Are there any patterns or examples of a good way to do this?

推荐答案

使用 ViewModel.

Use a ViewModel.

您有一个包含两个控件的视图.有一个视图模型,其中将包含要绑定到的 ListBox 控件的 ViewModel 列表.同样在此视图模型中,将列表框选择绑定到 TabControl 然后也绑定到的第二个视图模型列表.

You've got a View that contains the two controls. Have a view model that will contain a list of ViewModels for the ListBox control to bind to. Also within this view model bind the listbox selection to a second list of viewmodels that the TabControl then also binds to.

这样您的列表框就可以驱动选项卡控件显示的内容,而无需将此信息输入模型,而模型应该不会注意到视图的存在.

That way your listbox drives what the tab control shows without this information entering the model which should stay oblivious to the existence of the view.

这篇关于在 ViewModel 之间共享状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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