This project is read-only.

Design-time view models: Which approach is best with MtPage?

Aug 14, 2014 at 12:02 AM
Hi Rico,

Thanks for your excellent work on this toolkit. I have a question about how to cause VS to load different ViewModels for a single page depending on whether the page is in design mode or not.

In the documentation (https://mytoolkit.codeplex.com/wikipage?title=ViewModelBase&referringTitle=MVVM%20Overview) you describe:

"We recommend to instantiate the view model as resource because this adds code completion to the XAML editor: "
<Paging:MtPage ...>
    <Paging:MtPage.Resources>
        <ViewModels:MyViewModel x:Key="ViewModel" />
    </Paging:MtPage.Resources>

    <Grid DataContext="{StaticResource ViewModel}">
    ...
    </Grid>
</Paging:MtPage>
Is it possible to combine this approach with the <d:Page.Resources> tag? I'm guessing not, but perhaps you know of a better way? Ideally I'd like to do something like this:
<Paging:MtPage ...>
    <Paging:MtPage.Resources>
        <ViewModels:MyRealViewModel x:Key="ViewModel" />
    </Paging:MtPage.Resources>
    <? Design time resources tag ?>
        <ViewModels:MyFakeViewModel x:Key="ViewModel" />
    </? Design time resources tag ?>

    <Grid DataContext="{StaticResource ViewModel}">
    ...
    </Grid>
</Paging:MtPage>
Aug 14, 2014 at 12:13 AM
It's late in the day and I must be running low on caffeine. A straightforward way to do this is:
<Paging:MtPage ...>
    <Paging:MtPage.Resources>
        <ViewModels:MyRealViewModel x:Key="ViewModel" />
        <ViewModels:MyFakeViewModel x:Key="FakeViewModel" />
    </Paging:MtPage.Resources>

    <Grid DataContext="{StaticResource ViewModel}" d:DataContext="{StaticResource FakeViewModel}">
    ...
    </Grid>
</Paging:MtPage>
<facepalm>
Aug 14, 2014 at 7:49 AM
The only downside to this is that the fake view model is instantiated on app runtime even if it is not used...

Maybe you can set the view model this way (it works for code completion/intellisense in the XAML editor, but im not sure if the designer works correctly):
<Paging:MtPage.Resources>
    <ViewModels:MyRealViewModel x:Key="ViewModel" />
</Paging:MtPage.Resources>
<Grid DataContext="{StaticResource ViewModel}" d:DataContext="{d:DesignInstance Type=ViewModels:MyFakeViewModel}">
...
Another way is to use the ViewModel Locator pattern (I don't like it):
http://www.johnpapa.net/simple-viewmodel-locator-for-mvvm-the-patients-have-left-the-asylum/