WPF将不同的形状绑定到ItemsControl中的DataTemplate



我想将不同的System.Windows.Shapes.Shape绑定到ItemsControl中的DataTemplate。我有以下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>

如果我绑定一个形状,如椭圆(如示例)或矩形或多边形,它是完美的工作,但我需要在同一时间有不同的形状,如多边形和椭圆。我尝试使用ContentControl将DataTemplate关联到一个形状类型的对象PartShape:

<ItemsControl.ItemTemplate>
<DataTemplate>
<ContentControl Content="{Binding PartShape}" />
</DataTemplate>
</ItemsControl.ItemTemplate>

在虚拟机上的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;
}
}

绑定是ok的并且没有给出错误,但是它不起作用,它在画布上没有画任何东西。我该怎么办呢?

谢谢。

你需要给形状上色。已添加但不可见

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; }
}

最新更新