【发布时间】:2021-04-23 13:55:05
【问题描述】:
我想将不同的 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;
}
}
绑定没问题,没有错误,但它不起作用,它在画布上什么也没画。 我该怎么办?
谢谢。
【问题讨论】:
-
您没有设置填充或描边。形状在那里但不可见
标签: c# wpf data-binding datatemplate drawing2d