问题描述
我想将不同的 System.Windows.Shapes.Shape 绑定到 ItemsControl 中的 DataTemplate。 我有以下 ItemsControl 基于具有位置和形状信息的数组在 Canvas 上绘制形状:
<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>
如果我绑定像椭圆(如示例)或矩形或多边形这样的形状,它是完美的工作,但我需要同时拥有不同的形状,如多边形和椭圆。 我尝试使用 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;
}
}
绑定没问题,没有错误,但它不起作用,它在画布上什么也没画。 我该怎么办?
谢谢。
解决方法
你需要给形状上色。它已添加但不可见。
System.Windows.Shapes.Shape r = new System.Windows.Shapes.Ellipse
{
Width = 20,Height = 5,Fill = Brushes.Blue
};
public System.Windows.Shapes.Shape PartShape
{
get { return r; }
}