【问题标题】:How can you add Children to an ItemsPanelTemplate of an ItemsControl in WPF?如何在 WPF 中将子项添加到 ItemsControl 的 ItemsPanelTemplate?
【发布时间】:2021-04-22 11:53:30
【问题描述】:

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

【问题讨论】:

  • 请注意,为了绘制中心圆,您可以在 ItemTemplate 中使用带有 EllipseGeometry 的 Path 而不是 Ellipse。

标签: wpf xaml canvas itemscontrol


【解决方案1】:

您可以将椭圆添加到 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>

【讨论】:

  • 工作得很好。所以一个人需要两个画布,还是它们相互引用?
  • 第二个是在ItemsPresenter指定的地方创建的。最好用常规的 Grid 替换第一个。
  • 网格并不好。关键是在 ControlTemplate 中还有另一个 suitable Panel 元素。是嵌套画布还是其他面板取决于您的实际布局约束。 ControlTemplate 也是您通常放置 ScrollViewer 以防 ItemsControl 需要可滚动的地方。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-10-29
  • 2010-11-11
  • 2016-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多