uwpnestedthisdatatemplatedatatemplateselector

UWP use a datatemplate inside a datatemplate


Lets say I have class A, and B, which B : A. Now Lets say I have a datatemplate for class A: Atemplate, and now I want to create a datatemplate for class B : Btemplate which will use Atemplate and will have more elements. What element do I need to use in Btemplate in order to use Atemplate in it? I have tried ContentPresenter but I failed to understand how to bind the datacontext of the Btemplate (the 'this') to the ContentPresenter.Content property.

This is the ContentPresenter I tried to use:

<DataTemplate
    x:Key="Btemplate"
    x:DataType="namespace:B">
    <TextBlock Text="{x:bind name}" />
    <ContentPresenter
        Content="{x:Bind (namespace:B)}"
        ContentTemplateSelector="{StaticResource ADataTemplateSelector}" />
</DataTemplate>

I tried to bind 'this' to the ContentPresenter.Content using (namespace:B) which I have found in the docs of binding but it showed in the DataTemplateSelector that the item that is being binded is null.


Solution

  • UWP use a datatemplate inside a datatemplate

    What you've tried seems to be very close to work. I've made a demo about this. First, I created a TemplateA and a TemplateB which uses TemplateA as template. Then I use a ContentPresenter to check the behavior.

    Code:

      <Page.Resources>
        <DataTemplate x:Key="TemplateA" x:DataType="x:String">
            <StackPanel Background="Yellow">
                <TextBlock Text="{Binding}" />
                <TextBlock Foreground="Red" Text="TemplateA"/>
            </StackPanel>
        </DataTemplate>
    
        <DataTemplate x:Key="TemplateB" x:DataType="x:String">
            <StackPanel >
                <TextBlock Foreground="BlueViolet" Text="TemplateB"/>
                
                <ContentPresenter Content="{Binding}" ContentTemplate="{StaticResource TemplateA}"/>
            </StackPanel>
        </DataTemplate>
        
    </Page.Resources>
    
    <Grid>
        <ContentPresenter Content="12312313" ContentTemplate="{StaticResource TemplateB}"/>
    </Grid>
    

    Result:

    enter image description here