2012-09-20 65 views
1

我實現了CustomDataTemplateSelector喜歡這裏:​​。但是,在我的解決辦法只有一個,通過所有的DataTemplates改變部分的DataTemplates的其他部分是共同的:複雜數據模板

<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> 

這裏GRID1GRID2是不同的部分。是否有可能「拆分」這些DataTemplates?

回答

1

嘗試類似聲明的公用部分資源並將其綁定到一個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> 
+0

在這種情況下,綁定不起作用。 – Buddy

+0

如果設置Content =「{Binding}」,它就會工作。 – Buddy

+0

對不起,我忘了設置內容屬性!很高興您將其標記爲已接受! – michele