带有静态内容和项的画布



我有一个包含静态元素的Canvas-这些元素使用绑定将其绘制在正确的位置。现在我需要根据集合中的项绘制其他元素。我想用ItemsControl,但我不知道怎么做正确。我当前的伪代码:

<UserControl.Resources>
<RectangleGeometry x:Key="MyGeometry1">
<RectangleGeometry.Rect>
<MultiBinding Converter="{StaticResource RectConverter}">
<Binding Path="ActualWidth" ElementName="m_Canvas" />
<Binding Path="ActualHeight" ElementName="m_Canvas" />
</MultiBinding>
</RectangleGeometry.Rect>
</RectangleGeometry>
</UserControl.Resources>
<Canvas x:Name="m_Canvas">
<!-- "static" content -->
<Line x:Name="Line1" X1="{Binding Line1X1}" X2="{Binding Line1X2}" Y1="{Binding Line1Y1}" Y2="{Binding Line1Y2}"/>
<Line X1="0" X2="{Binding ActualWidth, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Canvas}}}" Y1="0" Y2="0">
<Path Fill="#35A500"
Opacity="0.15">
<Path.Data>
<GeometryGroup FillRule="EvenOdd">
<StaticResource ResourceKey="MyGeometry1" />
</GeometryGroup>
</Path.Data>
</Path>

<Line X1="{Binding Items[0].X1}" X2="{Binding Items[0].X2}" Y1="{Binding Items[0].Y1}" Y2="{Binding Items[0].Y2}"/>
<Line X1="{Binding Items[1].X1}" X2="{Binding Items[1].X2}" Y1="{Binding Items[1].Y1}" Y2="{Binding Items[1].Y2}"/>
<Line X1="{Binding Items[2].X1}" X2="{Binding Items[2].X2}" Y1="{Binding Items[2].Y1}" Y2="{Binding Items[2].Y2}"/>
</Canvas>

我试过这样做:

<ItemsControl ItemsSource="{Binding Items}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas>
<!-- "static" content -->
<Line x:Name="Line1" X1="{Binding Line1X1}" X2="{Binding Line1X2}" Y1="{Binding Line1Y1}" Y2="{Binding Line1Y2}"/>
<Line X1="0" X2="{Binding ActualWidth, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Canvas}}}" Y1="0" Y2="0">
</Canvas>
</ItemsPanelTemplate>
<!-- (...) other code -->
</ItemsControl>

但是我有一个错误:

错误XDG0062不能显式地修改作为ItemsControl的ItemsPanel的Panel的Children集合。ItemsControl为Panel生成子元素。

我理解这是因为我把Line1Canvas,但如何使这样的Canvas与某种静态内容,也作为一个容器的项目?

静态内容;可以放在ItemsControl的ControlTemplate中的ItemsPresenter的上方或下方的另一个Canvas中:

<ItemsControl ItemsSource="{Binding Items}">
<ItemsControl.Template>
<ControlTemplate TargetType="ItemsControl">
<Grid>
<Canvas>
<!-- "static" content -->
</Canvas>
<ItemsPresenter/>
</Grid>
</ControlTemplate>
</ItemsControl.Template>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>

最新更新