views:

36

answers:

1

I have following xaml code:

<Window x:Class="MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        DataContext="{Binding MainWindow, Source={StaticResource Locator}}">

    <Window.Resources>
        <DataTemplate DataType="{x:Type vm:KeyboardViewModel}">
            <vw:Keyboard />
        </DataTemplate>
        <DataTemplate DataType="{x:Type vm:WelcomeViewModel}">
            <vw:Welcome />
        </DataTemplate>


    </Window.Resources>
    <DockPanel>
        <DockPanel>
            <ContentControl Content="{Binding Path=Workspace}" />
        </DockPanel>
    </DockPanel>
</Window>

When Workspace is KeyboardViewModel, then the UserControl Keyboard is shown. When Workspace is Welcome, then the Welcome screen is shown. But when I test I mock the ViewModels with Moq. Workspace then get the type IKeyboardViewModelProxyxxxxxxxxxxxxx (where xxxxxxx is a random string), that don't maps to KeyboardViewModel in the DataTemplate and WPF don't now wish DataTemplate to show. When I use the real KeyboardViewModel, it is no problem. Can I fix it somehow, or do I have to redesign it?

A: 

You can omit the DataType="{x:Type vm:KeyboardViewModel}". If you do that, it is not expecting an instance of type KeyboardViewModel to bind against anymore but only an object of any type that just has all properties that are used in the template.

bitbonk
But if have multiple data templates, how do WPF know what it should choose? (I have updated my question to view it)
magol
In that case you would have to provide a TemplateSelector (if one ContentControl should dynamically take different templates) or tell the ContentControl what template to use via the ContentControl.ContentTemplate property (if one ContentControl should only take one template).
bitbonk