Home > Software design >  WPF explicit DataTemplate equivalent for implicit DataTemplate
WPF explicit DataTemplate equivalent for implicit DataTemplate

Time:09-26

By using implicit data template I can reference a template in a window resource without using a key in the template like so:

    <Window.Resources>
        <DataTemplate DataType="{x:Type viewModel:FriendDetailViewModel}">
            <view:FriendDetailView/>
        </DataTemplate>
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width= "200"/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <ContentControl Grid.Row="1" Grid.Column="1" Content="{StaticResource FriendDetailViewModel}">
        </ContentControl>
    </Grid>

i.e. the FriendDetailViewModel in the ContentControl can detect the FriendDetailViewModel in DataTemplate and display its contents properly.

But I'm trying to do it without an implicit data template, but I couldn't get the same result. For example, like this:

    <Window.Resources>
        <DataTemplate x:Key="FriendDetailViewData">
            <view:FriendDetailView DataContext="{Binding FriendDetailViewModel}"/>
        </DataTemplate>
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width= "200"/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <ContentControl Grid.Row="1" Grid.Column="1" Content="{Binding FriendDetailViewData}">
        </ContentControl>
    </Grid>

The ContentControl simply prints System.Windows.DataTemplate. Is there a way to get the equivalent behaviour without using implicit data template?

CodePudding user response:

The assignment

Content="{StaticResource FriendDetailViewData}"

makes no sense. It assigns the DataTemplate to the Content property.

You would still want to use a FriendDetailViewModel instance as Content and set the ContentTemplate explictly:

<Window.Resources>
    <DataTemplate x:Key="FriendDetailViewData">
        <view:FriendDetailView/>
    </DataTemplate>
</Window.Resources>

<ContentControl Content="{StaticResource FriendDetailViewModel}"
                ContentTemplate="{StaticResource FriendDetailViewData}"/>
  • Related