我想在一个画布上显示不同的形状(我在多张画布上有一个解决方案--但这不允许我选择所有的形状,所以它是毫无价值的)。我将形状放在一个CompositeCollection中,并在一个ItemsControl中使用多个DataTemplates。但是,程序不显示形状,而是在位置X,Y中显示属性名称。
这是收藏:
Page.Collection.Add(new CollectionContainer() { Collection = Page.Lines });
Page.Collection.Add(new CollectionContainer() { Collection = Page.Rectangles });
Page.Collection.Add(new CollectionContainer() { Collection = Page.Circles });这是类页面的一部分:
public class Page:ViewModelBase,INotifyPropertyChanged
{
ObservableCollection<Line> lines = new ObservableCollection<Line>();
ObservableCollection<Rectangle> rectangles = new ObservableCollection<Rectangle>();
ObservableCollection<Circle> circles = new ObservableCollection<Circle>();
CompositeCollection collection = new CompositeCollection();
public CompositeCollection Collection
{
get
{
return collection;
}
set
{
collection = value;
OnPropertyChanged("Collection");
}
}
public ObservableCollection<Line> Lines
{
get
{
return lines;
}
set
{
lines = value;
OnPropertyChanged("Lines");
}
}以下是XAML:
<ItemsControl ItemsSource="{Binding Page.Collection}" Grid.Row="1" Grid.Column="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas IsItemsHost="True" Grid.Row="1" Grid.Column="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
Background="Transparent">
</Canvas>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="Canvas.Left" Value="{Binding Start.X}"/>
<Setter Property="Canvas.Top" Value="{Binding Start.Y}"/>
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.Resources>
<DataTemplate DataType="Page.Lines">
<Line X1="{Binding Start.X}"
Y1="{Binding Start.Y}"
X2="{Binding End.X}"
Y2="{Binding End.Y}" Stroke="Black" StrokeThickness="1" />
</DataTemplate>
<DataTemplate DataType="Page.Rectangles">
<Rectangle
Width="{Binding Extend.X}"
Height="{Binding Extend.Y}" Stroke="Black" StrokeThickness="1" />
</DataTemplate>
<DataTemplate DataType="Page.Circles">
<Ellipse
Width="{Binding Extend.X}"
Height="{Binding Extend.Y}" Stroke="Black" StrokeThickness="1" />
</DataTemplate>
</ItemsControl.Resources>
</ItemsControl>发布于 2016-03-13 17:08:54
如果要通过DataType指定特定的类,则必须指定{x:Type ...}类型。没有这一点,就会像DataTemplate.DataType中所述的那样以XML元素为目标。
如果模板用于对象数据,则此属性包含数据对象的类型名称(作为字符串)。若要引用类的类型名称,请使用x:Type标记扩展。如果模板用于XML数据,则此属性包含XML元素名称。有关为XML元素指定非默认命名空间的详细信息,请参阅文档备注。
所以你的XAML应该是这样的
<DataTemplate DataType="{x:Type somenamespace:Line}">
<!-- removed content -->
</DataTemplate>
<DataTemplate DataType="{x:Type somenamespace:Rectangle}">
<!-- removed content -->
</DataTemplate>
<DataTemplate DataType="{x:Type somenamespace:Circle}">
<!-- removed content -->
</DataTemplate>其中somenamespace是定义Line、Rectangle和Circle类的命名空间。
xmlns:somenamespace="clr-namespace:Namespace.To.Your.Classes"https://stackoverflow.com/questions/35970119
复制相似问题