我在这里实现了 CustomDataTemplateSelector :Implementing Windows Phone 7 DataTemplateSelector and 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>
这里 Grid1 和 Grid2 是不同的部分。是否可以“拆分”这些DataTemplates?
答案 0 :(得分:1)
尝试将您的公共部分声明为Resource并将其绑定到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>