views:

307

answers:

2

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?

+7  A: 

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.

Graeme Bradbury
The View that contains the two controls is a Prism shell and the controls are in separate modules, but I think I can apply the principle. Thanks.
GraemeF
A: 

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.

Oleg Mihailik