Canvas 包含静态内容和项目

Canvas with static content and items

我有一个 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>

但是我有一个错误:

Error XDG0062 Cannot explicitly modify Children collection of Panel used as ItemsPanel for ItemsControl. ItemsControl generates child elements for Panel.

我知道那是因为我把 Line1 放在 Canvas 里面了,但是如何使这样的 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>