views:

530

answers:

2

Hi everybody, Does anybody have an idea how to change screens (views) in a MVVM View-First-Approach (The view instantiates the ViewModel:

DataContext="{Binding Source={StaticResource VMLocator},
Path=Find[EntranceViewModel]}"

)

For example: In my MainWindow (Shell) I show a entrance view with a Button "GoToBeach".

<Window>
  <DockPanel>
    <TextBox DockPanel.Dock="Top" Text="{Binding Title}" />
    <view.EntranceView DockPanel.Dock="Top" />    
  </DockPanel>
</Window>

When the button is clicked I want to get rid of the "EntranceView" and show the "BeachView". I am really curious if somebody knows a way to keep the View-First Approach and change the screen (view) to the "BeachView". I know there are several ways to implement it in a ViewModel-First Approach, but that is not the question. Perhabs I missed something in my mvvm investigation and can't see the wood for the trees... otherwise i am hoping for a inspiring discussion.

A: 

This looks like it might help: http://stackoverflow.com/questions/2688994/creating-a-viewmodel-do-it-before-or-after-model-data-is-available/2690607#2690607

Failing that, how about creating the ViewModel once only at startup, and assigning it to each View window as it's created (rather than creating a new ViewModel each time). Then just close the first View and open up a new View as required, reassigning the single ViewModel instance.

Surfbutler
VMLocator could have singleton instances of the ViewModels. Thats not the point. This question is just about a clean View-First-Approach, where every view creates its ViewModel or gets an instance of its view and not the opposite. When you assign a viewmodel to the content and handle the view via datatemplate, its a viewmodel-first apporach.
CodeWeasel
@CodeWeasel you sure? I think thats a View first approach.
Lisa
@Lisa: Can you please give me a further explanation?
CodeWeasel
A: 

One possibility would be to have all views in the (MainWindow(Shell) and using Triggers for their visibility. But having a lot of different screens (views) all declared in the MainWindow doesnt feel right for me...

This question came up while reading this nice way of using MEF with MVVM I found on John Papas Blog: Simple ViewModel Locator for MVVM: The Patients Have Left the Asylum . But as nice as this marriage of view and viewmodel is, it seems like there is no way to change screens that satisfies me. :)

So in my opinion if you have a lot of screens(views) you better use a ViewModel-First-Approach...

CodeWeasel