views:

27

answers:

1

I've got a View (MainView) which contains a kind of main content area (MainContent). The View is backed by a corresponding ViewModel (MainViewModel). The main content changes, of course, based on the current state of the application and is represented in the ViewModel as a property (CurrentPrimaryViewModel). The content of MainContent is bound to CurrentPrimaryViewModel in the XAML like so:

Content="{Binding Path=CurrentPrimaryViewModel}"

There's a ResourceDictionary containing a bunch of ViewModel->View mapping DataTemplates. So if the CurrentPrimaryViewModel is of type XViewModel, it resolves to XView.

This all works, kind of.

The problem is that every time the CurrentPrimaryViewModel changes a new View is created. What I'd like is for appropriately mapped View to simply have it's DataContext changed to the correct ViewModel and then have that View become the MainContent. Basically like the CardStack? layout from Java, or a TabControl without visible tabs.

What's the appropriate technique for handling this situation? Do I just have to create the various Views under the MainContent wrapper and toggle their visibility or Z-Order? Is there a good pattern for this? What should be bound between the MainView and MainViewModel in order to accomplish this?

A: 

AFAIK there is no control that can do this. However, it would seem to me that it would be spectacularly easy to do this (ignorance is bliss, you know). All you'd need to do is create a custom DataTemplateSelector that would cache the templates for your ContentControls.

Will
Wouldn't I have to create a custom DataTemplateSelector for each instance of MainContent that's aware of the various available DataTemplates. I just wrote up a little SelectorPanel with a CurrentItemKey dependency property and ItemKey attached property.The SelectorPanel just loops through the child controls and toggles their visibility based on if the ItemKey matches the CurrentItemKey.It's crude, but it works.
od9
@od9 a datatemplate is matched to a type. So all you'd have to do is create a single DataTemplateSelector as a resource and use it everywhere you need to share template instances. Within the DTS you'd just keep a dictionary of type/template instances and either new them up or send them out.
Will