.net “在使用 ItemsSource 之前,Items 集合必须为空。”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/683863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 12:23:56  来源:igfitidea点击:

"Items collection must be empty before using ItemsSource."

.netwpfvb.netentity-frameworkbinding

提问by Zack Peterson

I'm trying to get images to display in a WPF ListView styled like a WrapPanel as described in this old ATC Avalon Team article: How to Create a Custom View.

我正在尝试让图像显示在 WPF ListView 中,样式类似于 WrapPanel,如 ATC Avalon Team 旧文章中所述:如何创建自定义视图

When I try to populate the ListView with a LINQ-to-Entities queried collection of ADO.NET Entity Framework objects I get the following exception:

当我尝试使用 ADO.NET 实体框架对象的 LINQ-to-Entities 查询集合填充 ListView 时,出现以下异常:

Exception

例外

Items collection must be empty before using ItemsSource.

在使用 ItemsSource 之前,Items 集合必须为空。

My code…

我的代码…

Visual Basic

视觉基础

Private Sub Window1_Loaded(...) Handles MyBase.Loaded
    ListViewImages.ItemsSource = From g In db.Graphic _
                                 Order By g.DateAdded Ascending _
                                 Select g
End Sub

XAML

XAML

<ListView Name="ListViewImages"
          SelectionMode="Single"
          ItemsSource="{Binding}">
    <local:ImageView />
</ListView>

I put a breakpoint on that line. ListViewImages.ItemsSourceis Nothingjust before the LINQ assignment.

我在那条线上放了一个断点。 ListViewImages.ItemsSourceNothing刚刚LINQ分配之前。

采纳答案by Dave

The reason this particular exception gets thrown is that the content of the element gets applied to the ListView's Items collection. So the XAML initialises the ListView with a single local:ImageView in its Items collection. But when using an ItemsControl you must use either the Items property or the ItemsSource property, you can't use both at the same time. Hence when the ItemsSource attribute gets processed an exception is thrown.

引发此特定异常的原因是元素的内容被应用于 ListView 的 Items 集合。因此,XAML 使用其 Items 集合中的单个 local:ImageView 初始化 ListView。但是在使用 ItemsControl 时,您必须使用 Items 属性或 ItemsSource 属性,您不能同时使用两者。因此,当处理 ItemsSource 属性时,会引发异常。

You can find out which property the content of an element will get applied to by looking for the ContentPropertyAttribute on the class. In this case it's definedhigher in the class hierarchy, on the ItemsControl:

您可以通过在类上查找 ContentPropertyAttribute 来找出元素的内容将应用于哪个属性。在这种情况下,它在类层次结构中定义更高,在 ItemsControl 上:

[ContentPropertyAttribute("Items")]

The intention here was that the ListView's View be set to a local:ImageView so the fix is to explicitly indicate the property to be set.

这里的意图是将 ListView 的 View 设置为 local:ImageView 因此修复是明确指示要设置的属性。

Fix the XAML and the exception goes away:

修复 XAML,异常消失:

<ListView Name="ListViewImages"
          SelectionMode="Single"
          ItemsSource="{Binding}">
    <ListView.View>
        <local:ImageView />
    </ListView.View>
</ListView>

It was missing that <ListView.View>tag.

它缺少那个<ListView.View>标签。

回答by kenwarner

I had this same error for a while in a slightly different scenario. I had

在稍微不同的情况下,我有一段时间遇到了同样的错误。我有

<wpftoolkit:DataGrid
    AutoGenerateColumns="False"
    ItemsSource="{Binding Path=Accounts}" >
    <wpftoolkit:DataGridTextColumn 
        Header="Account Name" 
        Binding="{Binding Path=AccountName}" />
</wpftoolkit:DataGrid>

which I fixed to be

我确定是

<wpftoolkit:DataGrid
    AutoGenerateColumns="False"
    ItemsSource="{Binding Path=Accounts}" >
    <wpftoolkit:DataGrid.Columns>
        <wpftoolkit:DataGridTextColumn 
            Header="Account Name" 
            Binding="{Binding Path=AccountName}" />
    </wpftoolkit:DataGrid.Columns>
</wpftoolkit:DataGrid>

回答by Armentage

I just ran into a VERY insidious example of this problem. My original fragment was much more complex, which made it difficult to see the error.

我刚刚遇到了这个问题的一个非常阴险的例子。我的原始片段要复杂得多,这使得很难看到错误。

   <ItemsControl           
      Foreground="Black"  Background="White" Grid.IsSharedSizingScope="True"
      x:Name="MyGrid" ItemsSource="{Binding}">
      >
      <ItemsControl.ItemsPanel>
           <!-- All is fine here -->
      </ItemsControl.ItemsPanel>
      <ItemsControl.ItemTemplate>
           <!-- All is fine here -->
      </ItemsControl.ItemTemplate>
      <!-- Have you caught the error yet? -->
    </ItemsControl>

The bug? The extra >after the initial opening <ItemsControl>tag! The <got applied to the built-in Items collection. When the DataContext was later set, instant crashola. So look out for more than just errors surround your ItemsControl specific data children when debugging this problem.

错误?初始开始标记之后的额外><ItemsControl>!已<应用于内置 Items 集合。当稍后设置 DataContext 时,立即崩溃。因此,在调试此问题时,要注意的不仅仅是围绕 ItemsControl 特定数据子项的错误。

回答by Junior Mayhé

Me too on a different scenario.

我也是一个不同的场景。

<ComboBox Cursor="Hand" DataContext="{Binding}"  
              FontSize="16" Height="27" ItemsSource="{Binding}" 
              Name="cbxDamnCombo" SelectedIndex="0" SelectedValuePath="MemberId">

        <DataTemplate>
            <TextBlock DataContext="{Binding}">
                <TextBlock.Text>
                  <MultiBinding StringFormat="{}{0} / {1}">
                    <Binding Path="MemberName"/>
                    <Binding Path="Phone"/>
                  </MultiBinding>
                </TextBlock.Text>
            </TextBlock>
        </DataTemplate>

</ComboBox>

Now when you complete with the missing tag Control.ItemTemplate, everything gets to normal:

现在,当您完成缺少的标签Control.ItemTemplate 时,一切都会恢复正常:

<ComboBox Cursor="Hand" DataContext="{Binding}"  
              FontSize="16" Height="27" ItemsSource="{Binding}" 
              Name="cbxDamnCombo" SelectedIndex="0" SelectedValuePath="MemberId">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock DataContext="{Binding}">
                <TextBlock.Text>
                  <MultiBinding StringFormat="{}{0} / {1}">
                    <Binding Path="MemberName"/>
                    <Binding Path="Phone"/>
                  </MultiBinding>
                </TextBlock.Text>
            </TextBlock>
        </DataTemplate>
    <ComboBox.ItemTemplate>
</ComboBox>

回答by ehudbk

I had this same error in a different scenario

我在不同的场景中遇到了同样的错误

<ItemsControl ItemsSource="{Binding TableList}">
    <ItemsPanelTemplate>
        <WrapPanel Orientation="Horizontal"/>
    </ItemsPanelTemplate>
</ItemsControl>

The solution was to add the ItemsControl.ItemsPaneltag before the ItemsPanelTemplate

解决方案是在ItemsControl.ItemsPanel之前添加标签ItemsPanelTemplate

<ItemsControl ItemsSource="{Binding TableList}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel Orientation="Horizontal"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>

回答by ΩmegaMan

?? To state the answer differently??

?? 换个说法??

In Xamlverify that there are no Missing Parent Nodes or incorrect nodesin the defined areas.

在 Xaml 中验证定义的区域中没有缺失的父节点或不正确的节点

For example

例如

This Is Failing:

这是失败的:

There is no properparentfor the ItemsPanelTemplatechild node below:

下面的子节点没有合适的ItemsPanelTemplate节点:

<ItemsControl ItemsSource="{Binding TimeSpanChoices}">
    <ItemsPanelTemplate>
        <UniformGrid Rows="1" />
    </ItemsPanelTemplate>
    ...
</ItemsControl>

This Is Working:

这是有效的:

<ItemsControl ItemsSource="{Binding TimeSpanChoices}">
    <ItemsControl.ItemsPanel> <!-- I am the missing parent! -->
        <ItemsPanelTemplate>
            <UniformGrid Rows="1" />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    ...    
</ItemsControl>

There is a proper parent node of <ItemsControl.ItemsPanel>provided^^^.

有一个适当的父节点<ItemsControl.ItemsPanel>提供 ^^^。

回答by Bizhan

Exception

Items collection must be empty before using ItemsSource.

例外

在使用 ItemsSource 之前,Items 集合必须为空。

This exception occurs when you add items to the ItemsSourcethrough different sources. So Make sure you haven't accidentally missed a tag, misplaced a tag, added extra tags, or miswrote a tag.

当您ItemsSource通过不同的源向 中添加项目时会发生此异常。因此,请确保您没有意外遗漏标签、错放标签、添加额外标签或写错标签。

<!--Right-->

<ItemsControl ItemsSource="{Binding MyItems}">
     <ItemsControl.ItemsPanel.../>
     <ItemsControl.MyAttachedProperty.../>
     <FrameworkElement.ActualWidth.../>
</ItemsControl>


<!--WRONG-->

<ItemsControl ItemsSource="{Binding MyItems}">
     <Grid.../>
     <Button.../>
     <DataTemplate.../>
     <Heigth.../>
</ItemsControl>


While ItemsControl.ItemsSourceis already set through Binding, other items (Grid, Button, ...) can't be added to the source. However while ItemsSourceis not in-usethe following code is allowed:

虽然ItemsControl.ItemsSource已通过 设置Binding,但无法将其他项目(网格、按钮等)添加到源中。但是同时ItemsSource不是在使用下面的代码是允许的

<!--Right-->
<ItemsControl>
     <Button.../>
     <TextBlock.../>
     <sys:String.../>
</ItemsControl>

notice the missing ItemsSource="{Binding MyItems}"part.

注意缺失的ItemsSource="{Binding MyItems}"部分。

回答by Ram

Keep template column inside DataGrid.Columns. This helped me resolve this issue.

将模板列保留在 DataGrid.Columns 中。这帮助我解决了这个问题。

Ref: DataGridTemplateColumn : Items collection must be empty before using ItemsSource.

Ref: DataGridTemplateColumn : 在使用 ItemsSource 之前,Items 集合必须为空。

回答by samiz

In my case, it was not using a DataTemplate for the ItemsControl.

就我而言,它没有为 ItemsControl 使用 DataTemplate。

Old:

老的:

<ItemsControl Width="243" ItemsSource="{Binding List, Mode=TwoWay}">
    <StackPanel Orientation="Horizontal">
        <TextBox Width="25" Margin="0,0,5,0" Text="{Binding Path=Property1}"/>
        <Label Content="{Binding Path=Property2}"/>
    </StackPanel>
</ItemsControl>

New:

新的:

<ItemsControl Width="243" ItemsSource="{Binding List, Mode=TwoWay}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <TextBox Width="25" Margin="0,0,5,0" Text="{Binding Path=Property1}"/>
                <Label Content="{Binding Path=Property2}"/>
            </StackPanel>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

回答by PatFromCanada

Mine was with a datagrid Style. If you leave out the <DataGrid.RowStyle>tags around the Style you get that problem. Weird thing is it worked for a while like that. Here is the bad code.

我的是数据网格样式。如果你省略了<DataGrid.RowStyle>Style 周围的 标签,你就会遇到这个问题。奇怪的是它像那样工作了一段时间。这是错误的代码。

 <DataGrid Name="DicsountScheduleItemsDataGrid"
                  Grid.Column="0"
                  Grid.Row="2"
                  AutoGenerateColumns="false"
                  ItemsSource="{Binding DiscountScheduleItems, Mode=OneWay}">
            <Style TargetType="DataGridRow">
                <Setter Property="IsSelected"
                        Value="{Binding IsSelected, Mode=TwoWay}" />
            </Style>

and the good

和好的

 <DataGrid Name="DicsountScheduleItemsDataGrid"
                  Grid.Column="0"
                  Grid.Row="2"
                  AutoGenerateColumns="false"
                  ItemsSource="{Binding DiscountScheduleItems, Mode=OneWay}">
            <DataGrid.RowStyle>
            <Style TargetType="DataGridRow">
                <Setter Property="IsSelected"
                        Value="{Binding IsSelected, Mode=TwoWay}" />
            </Style>
            </DataGrid.RowStyle>