我想将多个类型的集合绑定到在画布中显示的ItemsControl.到目前为止,我的代码如下:
<ItemsControl ItemsSource="{Binding Path=Objects}">
<ItemsControl.Resources>
<DataTemplate DataType="self:CalibrationRectangle">
<Rectangle Fill="{Binding Path=Color, Converter={StaticResource ColorToBrushConverter}}" Width="{Binding Width}" Height="{Binding Height}" />
</DataTemplate>
<DataTemplate DataType="self:PolygonVM">
<Polygon Fill="{Binding Path=Color, Converter={StaticResource ColorToBrushConverter}}" Points="{Binding Points}" />
</DataTemplate>
</ItemsControl.Resources>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas Background="Red" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<!--<ItemsControl.ItemTemplate>
<DataTemplate DataType="self:CalibrationRectangle">
<Rectangle Fill="{Binding Path=Color, Converter={StaticResource ColorToBrushConverter}}" Width="{Binding Width}" Height="{Binding Height}" />
</DataTemplate>
</ItemsControl.ItemTemplate>-->
<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="Canvas.Top" Value="{Binding Path=Y}" />
<Setter Property="Canvas.Left" Value="{Binding Path=X}" />
</Style>
</ItemsControl.ItemContainerStyle>
</ItemsControl>
Run Code Online (Sandbox Code Playgroud)
在此代码状态中,资源中的DataTemplates被完全忽略,而对象则表示为字符串.相反,我使用注释掉的行并在ItemsControl.ItemsTemplate中定义DataTemplate它的工作原理.但是,由于我需要多个DataTemplates(每种类型一个),这不是解决方案.
这里有什么问题?为什么资源中的DataTemplates不起作用?
任何想法都赞赏:)