首页 > 解决方案 > 如何在 WPF 中将子项添加到 ItemsControl 的 ItemsPanelTemplate?

问题描述

我有以下 ItemsControl:

<ItemsControl ItemsSource="{Binding ControllableLedList}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <Canvas Width="600" Height="600" Grid.Row="0" Grid.Column="0" Background="FloralWhite" >
                <Ellipse Width="600" Height="600" Fill="#FF252525" /> <!-- big Ellipse causing my error -->
            </Canvas>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemContainerStyle>
        <Style TargetType="ContentPresenter">
            <Setter Property="Canvas.Left" Value="{Binding PositionX}" />
            <Setter Property="Canvas.Top" Value="{Binding PositionY}" />
        </Style>
    </ItemsControl.ItemContainerStyle>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Ellipse  Width="5" Height="5" Fill="Yellow"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

基本上这里的想法是有一个带有椭圆集合的画布(我们称它们为 LED,因为它们在现实世界中所代表的),其中 LED 椭圆的位置由ViewModel 上面的代码控制,除了画布中的大椭圆 -> 添加后,我收到以下错误:

InvalidOperationException:无法显式修改用作 ItemsControl 的 ItemsPanel 的 Panel 的 Children 集合。ItemsControl 为 Panel 生成子元素

这是有道理的,因为“实际的孩子 - LED 椭圆”应该在运行时动态生成。无论如何,我怎样才能让我的大椭圆进入我的画布,以便可见性的顺序是Canvas.Background-> Big Ellipse-> LED Ellipses

标签: wpfxamlcanvasitemscontrol

解决方案


您可以将椭圆添加到 ItemsControl 的模板中:

<ItemsControl.Template>
    <ControlTemplate TargetType="ItemsControl">
        <Canvas>
            <Ellipse Width="600" Height="600" Fill="#FF252525" />
            <ItemsPresenter/>
        </Canvas>
    </ControlTemplate>
</ItemsControl.Template>
<ItemsControl.ItemsPanel>
    <ItemsPanelTemplate>
        <Canvas/>
    </ItemsPanelTemplate>
</ItemsControl.ItemsPanel>

推荐阅读