Question

I've implemented CustomDataTemplateSelector like here: Implementing Windows Phone 7 DataTemplateSelector and CustomDataTemplateSelector. But in my solution there is only one part that changes through all DataTemplates, other parts of DataTemplates are common:

<local:MyTemplateSelector Content="{Binding}">
    <local:MyTemplateSelector.OneTemplate>
        <DataTemplate>
            <Grid Orientation="Horizontal" >
                <Grid x:Name="Grid1">
                    <Image Height="60" Width="60" Source="{Binding Photo}"/>
                </Grid>
                <Grid>
                    <TextBlock Text="{Binding TextValue1}">
                    <TextBlock Text="{Binding TextValue2}">
                </Grid>
            </Grid>
        </DataTemplate>
    </local:MyTemplateSelector.OneTemplate>
    <local:MyTemplateSelector.AnotherTemplate>
        <DataTemplate>
            <Grid Orientation="Horizontal" >
                <Grid x:Name="Grid2">
                    <Image Height="30" Width="60" Source="{Binding Photos[0]}"/>
                    <Image Height="30" Width="60" Source="{Binding Photos[1]}"/>
                </Grid>
                <Grid>
                    <TextBlock Text="{Binding TextValue1}">
                    <TextBlock Text="{Binding TextValue2}">
                </Grid>
            </Grid>
        </DataTemplate>
    </local:MyTemplateSelector.AnotherTemplate>
</local:MyTemplateSelector>

Here Grid1 and Grid2 are different parts. Is it possible to "split" these DataTemplates?

Was it helpful?

Solution

Try something like declare your common part as Resource and bind it to a ContentPresenter:

<DataTemplate x:Key="CommonPart">
   <Grid >
      <TextBlock Text="{Binding TextValue1}">
      <TextBlock Text="{Binding TextValue2}">
   </Grid>
</DataTemplate>

<local:MyTemplateSelector Content="{Binding}">
<local:MyTemplateSelector.OneTemplate>
<DataTemplate>
   <Grid Orientation="Horizontal" >
      <Grid x:Name="Grid1">
         <Image Height="60" Width="60" Source="{Binding Photo}"/>
      </Grid>
      <ContentPresenter ContentTemplate="{StaticResource CommonPart}" />                
   </Grid>
</DataTemplate>
</local:MyTemplateSelector.OneTemplate>
<local:MyTemplateSelector.AnotherTemplate>
<DataTemplate>
   <Grid Orientation="Horizontal" >
      <Grid x:Name="Grid2">
         <Image Height="30" Width="60" Source="{Binding Photos[0]}"/>
         <Image Height="30" Width="60" Source="{Binding Photos[1]}"/>
      </Grid>
      <ContentPresenter ContentTemplate="{StaticResource CommonPart}" /> 
   </Grid>
</DataTemplate>
</local:MyTemplateSelector.AnotherTemplate>
</local:MyTemplateSelector>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top