【发布时间】:2016-09-20 15:50:51
【问题描述】:
在我当前的项目中,我有一个嵌套的数据结构。根是 ObservableCollection (terrainModel.terrainElements)。集合中的每个元素都承载另一个 ObservableCollection(drawElements),该 ObservableCollection(drawElements) 包含用于在画布中绘制图元的数据。根据原语,我提供了一个 DataTemplate 以便它在 Canvas 中呈现。
这是实际的 XAML:
<ItemsControl ItemsSource="{Binding terrainModel.terrainElements}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas Width="1000" Height="500" Background="Aquamarine"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<ItemsControl ItemsSource="{Binding drawElements}">
<ItemsControl.Resources>
<DataTemplate DataType="{x:Type drawtype:LineElement}">
<Line Stroke="Black" X1="{Binding startPoint.X}" Y1="{Binding startPoint.Y}" X2="{Binding endPoint.X}" Y2="{Binding endPoint.Y}" />
</DataTemplate>
<DataTemplate DataType="{x:Type drawtype:CircleElement}">
<Ellipse Stroke="Black" Width="{Binding radius}" Height="{Binding radius}"/>
</DataTemplate>
<DataTemplate DataType="{x:Type drawtype:RectangleElement}">
<Rectangle Stroke="Blue" Width="{Binding width}" Height="{Binding height}" Canvas.Left="{Binding position.X}" Canvas.Top="{Binding position.Y}"/>
</DataTemplate>
</ItemsControl.Resources>
</ItemsControl>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
但问题是我无法在 XAML 中正确设置基元的位置,例如 Canvas.Left="{Binding position.X}" 无法正常工作,因为它在内部 ItemsControl 和不在外部 ItemsControl 中。
我也尝试像这样转换原语:
<Rectangle.RenderTransform><TranslateTransform x:Name="myTransform2" X="{Binding position.X}" Y="{Binding position.Y}" /></Rectangle.RenderTransform>
这有效,但破坏了要绘制的以下元素的位置。当然我可以在视图的代码中绘制所有内容,但我想知道是否也可以在 xaml 中进行。
【问题讨论】: