【发布时间】:2015-07-14 20:33:30
【问题描述】:
我想将多个类型的集合绑定到画布中显示的 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>
在这种代码状态下,资源中的 DataTemplates 被完全忽略,而是将对象表示为字符串。 相反,如果我使用注释掉的行并在 ItemsControl.ItemsTemplate 中定义 DataTemplate 它可以工作。但是,由于我需要多个 DataTemplates(每种类型一个),这不是解决方案。
这里有什么问题?为什么资源中的 DataTemplates 不起作用?
感谢任何想法:)
【问题讨论】:
-
self:CalibrationRectangle和selfPolygonVM是什么?因为在我看来,您正在将您的DataTemplate应用于您的ItemsControl中未使用的类型 -
这些只是一些自己的类型,具有绑定字段作为属性。它们都有相同的父类型,称为 DrawableVM。绑定的集合 Objects 只是一个 ObservableCollection
。所以我的 ItemsControl 应该使用这些类型,还是我得到了一些破旧的东西?
标签: c# wpf xaml datatemplate itemscontrol