因此,我有一个ItemsControl和一个ItemTemplate来可视化它的ItemsSource中的项目。此模板是一个DataTemplate,其中包含一些控件。
<ItemsControl ItemsSource="{Binding Items}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock/>
<TextBlock/>
<!-- Content depending on item type -->
<ContentPresenter Content="{Binding}" ContentTemplateSelector="{StaticResource TemplateSelector}"/>
<TextBlock/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>ItemsSource中的项可以是不同类型的。不同类型的大多数属性是相同的,但有些属性是不同的。因此,我希望将公共内容直接放在DataTemplate中,但是对于不同的内容,我希望有某种占位符,它只显示特定类型的内容。
所以我尝试了一个ContentPresenter和一个ContentTemplateSelector。但这行不通。当我设置内容时,永远不会调用TemplateSelector,并显示底层视图模型的名称。当我不设置内容时,将调用TemplateSelector,但SelectTemplate函数中的项为null。
我不想为每个DataTemplate制作整个DataType,因为大多数内容是相同的,而且我会有很多重复的代码。
发布于 2021-06-08 09:20:40
您不需要DataTemplateSelector。
只需在ItemsControl的参考资料中设置不同DataType的DataTemplates即可。将根据项目的类型自动选择DataTemplates。
<ItemsControl ItemsSource="{Binding Items}">
<ItemsControl.Resources>
<DataTemplate DataType="{x:Type local:Item1}">
<TextBlock Text="{Binding Item1Property}"/>
</DataTemplate>
<DataTemplate DataType="{x:Type local:Item2}">
<TextBlock Text="{Binding Item2Property}"/>
</DataTemplate>
</ItemsControl.Resources>
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock ... />
<ContentPresenter Content="{Binding}"/>
<TextBlock ... />
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>https://stackoverflow.com/questions/67884435
复制相似问题