Sharing state between ViewModels

假如想象 提交于 2020-01-13 04:28:25

问题


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.

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.

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?


回答1:


Use a ViewModel.

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.




回答2:


TabControl is ItemsControl, so you shouldn't be shy to bind its ItemsSource to ListBox.SelectedITems.

Obviously ViewModel for List should have a property that would produce ViewModel for Tabs:

public TabViewModel ItemTabModel { get { ... } }

And because TabControl is a bit funny, you'd need to add ItemContainerStyle to populate Content for TabControlItem, because the normal ItemTemplate for TableControl only affects headers for tabs.



来源:https://stackoverflow.com/questions/1159035/sharing-state-between-viewmodels

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!