Associate User Control with ViewModel class

Viewed 116

When I define a DataTemplate inline, Visual Studio knows about the type I'm binding to, and properties in that type come up in autocomplete (for example in the code below I was able to select DisplayName from the autocomplete list inside the FirstViewModel template).

<DataTemplate DataType="{x:Type viewmodels:FirstViewModel}">
    <StackPanel >
        <Label Content="{Binding DisplayName}"/>
    </StackPanel>
</DataTemplate>

<DataTemplate DataType="{x:Type viewmodels:SecondViewModel}">
    <views:SecondView/>
</DataTemplate>

However, when the data template references an external control, as for SecondViewModel in the code above, when I'm in the file for the SecondView usercontrol, since it's just a control, the type isn't bound and the editor doesn't help me with anything.

I've tried wrapping my whole control (inside the UserControl element) in the same DataTemplate tag, but then my whole view just shows "System.Windows.DataTemplate".

<UserControl x:Class="Gui.Views.Tabs.ExamsTabViews.ExamInfoView"
             xmlns:vm="clr-namespace:Gui.ViewModels"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800">

    <DataTemplate DataType="vm:ExamInfoViewModel">
        <DockPanel VerticalAlignment="Stretch" HorizontalAlignment="Stretch">

            <!-- contents of the template -->             

        </DockPanel>
    </DataTemplate>
</UserControl>

Is there a way to achieve this kind of binding for the editor?

1 Answers
<DataTemplate DataType="{x:Type viewmodels:SecondViewModel}">
    <views:SecondView/>
</DataTemplate>

when this DataTemplate is instantiated, there will be created SecondView and that SecondView will have a SecondViewModel in DataContext. So there is no need any DataTemplate in SecondViewModel control - bind to DataContext instead ({Binding SecondViewModelProperty}). To have design-time support for such binding use d:DataContext="{d:DesignInstance}:

<UserControl d:DataContext="{d:DesignInstance Type=vm:ExamInfoViewModel, 
                             IsDesignTimeCreatable=True}" ...>
Related