我实现了CustomDataTemplateSelector,如下所示:Windows 7 DataTemplateSelector和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是可能的吗?
发布于 2012-09-20 08:20:35
尝试将公共部分声明为资源,并将其绑定到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>https://stackoverflow.com/questions/12508303
复制相似问题