【发布时间】:2022-03-04 03:42:23
【问题描述】:
我正在尝试将 itemscontrol 绑定到另一个集合内的集合。为此,我在另一个 itemscontrol 中分层了一个 itemscontrol,如下所示:
<ItemsControl ItemsSource="{Binding MachinistUnreportedOps}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Grid />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<ItemsControl ItemsSource="{Binding MultiJobOps}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Grid />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<DataTemplate>
<TextBlock>
<Run Text="Op " />
<Run Text="{Binding JobOperation}" />
</TextBlock>
</DataTemplate>
</ItemsControl>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
这最终将绑定到实体框架的源,但由于我遇到问题,我只是将这个虚拟数据放在我的视图模型中:
MachinistUnreportedOps = new ObservableCollection<SimpleClass>()
{
new()
{
MultiJobOps = new()
{
new() { JobOperation = 100 },
new() { JobOperation = 101 },
new() { JobOperation = 102 },
},
},
new()
{
MultiJobOps = new()
{
new() { JobOperation = 103 },
new() { JobOperation = 104 },
new() { JobOperation = 105 },
},
},
};
(SimpleClass 几乎只是保存一些数据,我试图在上面的 xaml 中访问这些数据。显然它有一个 JobOperation 属性,这是一个 int。)
不幸的是,这些数据和使用 EF 时会出现同样的问题:
System.Windows.Markup.XamlParseException: 'Add value to collection of type 'System.Windows.Controls.ItemCollection' threw an exception.'
内部异常:
System.InvalidOperationException: Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead.
我已经调查过这个错误,但大多数问题(比如这个:Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead)似乎是关于直接访问控件并更改其中的项目,而我根本没有这样做。在我的代码或视图模型中,我没有引用任何 itemcontrol。我什至没有在其他任何地方访问我的代码中的MachinistUnreportedOps 集合,更不用说修改它了。我想我一定误解了ItemsControl 如何处理其绑定数据。我对 WPF 还是很陌生。
我确实找到了一篇文章,我丢失了链接,但它建议定义一个项目面板,就像我在上面的 xaml 中所做的那样。一种或另一种方式的行为没有区别。我不太在意使用什么样的面板,但网格对于内部项目控件来说会很好,因为我希望扩展它。
【问题讨论】:
-
问题出在你的内部 ItemsControl -- 绑定到
MultiOpJobs的那个。你有一个 DataTemplate ,但你忘了把它放在<ItemsControl.ItemTemplate>标签内
标签: c# wpf xaml data-binding itemscontrol