wpf - 如何在 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
?
解决方案
您可以将椭圆添加到 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>
推荐阅读
- azure-devops - Azure 管道运行时评估的变量传递了一个参数
- javascript - 最简单的是在 javascript 中显示未定义的元素
- prometheus - 如何在 Prometheus 中使用时间单位创建警报?比如“最近 2 分钟平均响应时间超过 5 秒”
- python - 减去从字符串转换的日期时间时,total_seconds() 是错误的
- vba - 使用文本框内容宏重命名 Powerpoint 对象
- javascript - 混淆更新根目录并在链接中添加文本
- python - 如何在唯一列值上合并数据框?
- vue.js - Vue Router 的资源路径在重新加载时中断
- ruby-on-rails - 为什么 Rails 应该渲染 422 却渲染 200?
- c++ - C++ 模板类的内部类访问