簡體   English   中英

如何將子項添加到 WPF 中 ItemsControl 的 ItemsPanelTemplate?

[英]How can you add Children to an ItemsPanelTemplate of an ItemsControl in WPF?

我有以下 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>

基本上這里的想法是擁有一個帶有橢圓集合的 canvas(我們稱它們為 LED,因為它們在現實世界中所代表的),其中 LED 橢圓的 position 由ViewModel控制。上面的代碼運行良好,除了Canvas 中的大橢圓 -> 添加后,我收到以下錯誤:

InvalidOperationException:無法顯式修改用作 ItemsControl 的 ItemsPanel 的 Panel 的 Children 集合。 ItemsControl 為 Panel 生成子元素

這是有道理的,因為“實際的孩子 - LED 橢圓”應該在運行時動態生成。 無論如何,我怎樣才能讓我的大橢圓進入我的 canvas,以便可見性的順序是Canvas.Background -> Big Ellipse -> LED Ellipses

您可以將橢圓添加到 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM