我想将不同的 System.Windows.Shapes.Shape 绑定到 ItemsControl 中的 DataTemplate。我基于具有位置和形状信息的数组在 Canvas 上绘制了以下 ItemsControl 形状:
<ItemsControl Width="800" ItemsSource="{Binding ShapesPositionArray}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas Name="sequenceCanvas" Width="800" Height="800" ClipToBounds="True"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style TargetType="ContentPresenter">
<Setter Property="Canvas.Left" Value="{Binding X}"/>
<Setter Property="Canvas.Top" Value="{Binding Y}"/>
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Ellipse Width="5" Height="5" Fill="Black"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
如果我与 Ellipse(如示例)或 Rectangle 或 Polygon 之类的 Shape 绑定,它可以完美地工作,但我需要同时具有不同的形状,例如 Polygons 和 Ellipses。我尝试使用 ContentControl 将 DataTemplate 关联到 Shapes 类型的对象 PartShape:
<ItemsControl.ItemTemplate>
<DataTemplate>
<ContentControl Content="{Binding PartShape}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
VM 中的 PartShape 是这样的对象:
public System.Windows.Shapes.Shape PartShape
{
get
{
System.Windows.Shapes.Shape r = new System.Windows.Shapes.Ellipse();
r.Width = 20;
r.Height = 5;
return r;
}
}
绑定没问题,没有错误,但它不起作用,它在画布上什么也没画。我该怎么办?
谢谢。