我正在嘗試將 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.
I've looked into this error, but most issues (like this one: Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead) seem to be about directly accessing the control and changing the items in it, which I'm not doing at all. I have no references to either itemscontrol in my code behind or viewmodel. I'm not even accessing the MachinistUnreportedOps collection in my code anywhere else, let alone modifying it. I figure I must be misunderstanding something about how ItemsControl works with its bound data. I'm still pretty new to WPF.
我確實找到了一篇文章,我丟失了鏈接,但它建議定義一個專案面板,就像我在上面的 xaml 中所做的那樣。一種或另一種方式的行為沒有區別。我不太在意使用什么樣的面板,但網格對于內部專案控制元件來說會很好,因為我希望擴展它。
uj5u.com熱心網友回復:
以答案的形式提出。您的 XAML 應該如下所示。我所做的唯一更改是將您的第二個DataTemplate放入<ItemsControl.ItemTemplate>標簽中。因為這就是它存在的原因;您正在使用它來圍繞它設定 ItemsControl 的 ItemTemplate 屬性。
<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>
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock>
<Run Text="Op " />
<Run Text="{Binding JobOperation}" />
</TextBlock>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/437171.html
