WPF 将不同的形状绑定到 ItemsControl 中的 DataTemplate
WPF binding different Shapes to a DataTemplate in an ItemsControl
我想将不同的 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>
如果我绑定像椭圆(如示例)或矩形或多边形这样的形状,它会完美地工作,但我需要同时具有不同的形状,如多边形和椭圆。
我尝试使用 ContentControl 将 DataTemplate 关联到 Shapes 类型的对象 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;
}
}
绑定没问题,没有报错,但它不起作用,它在 canvas 上什么也没画。
我该怎么办?
谢谢。
您需要给形状上色。它已添加但不可见。
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; }
}
我想将不同的 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>
如果我绑定像椭圆(如示例)或矩形或多边形这样的形状,它会完美地工作,但我需要同时具有不同的形状,如多边形和椭圆。 我尝试使用 ContentControl 将 DataTemplate 关联到 Shapes 类型的对象 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;
}
}
绑定没问题,没有报错,但它不起作用,它在 canvas 上什么也没画。 我该怎么办?
谢谢。
您需要给形状上色。它已添加但不可见。
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; }
}