【问题标题】:"Items collection must be empty before using ItemsSource."“在使用 ItemsSource 之前,项目集合必须为空。”
【发布时间】:2010-10-15 14:15:09
【问题描述】:

我正在尝试让图像显示在 WPF ListView 中,其样式类似于 WrapPanel,如旧 ATC Avalon 团队文章中所述:How to Create a Custom View

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

例外

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

我的代码……

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

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

我在那行放了一个断点。 ListViewImages.ItemsSource 在 LINQ 分配之前是 Nothing

【问题讨论】:

    标签: .net wpf vb.net entity-framework binding


    【解决方案1】:

    在稍有不同的情况下,我曾有一段时间遇到同样的错误。原因是 XAML 无效,因为缺少某些标记。

    我有

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

    我固定的

    <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>
    

    【讨论】:

    • 谢谢!如此简单的问题……却如此令人困惑的错误。
    • 对我来说,区别只是缺少 (我什至没有使用 wpftoolkit)。
    • 我也缺少
    【解决方案2】:

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

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

    [ContentPropertyAttribute("Items")]
    

    这里的意图是将 ListView 的 View 设置为 local:ImageView,因此解决方法是明确指示要设置的属性。

    修复 XAML,异常消失:

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

    缺少&lt;ListView.View&gt; 标签。

    【讨论】:

    • 这个答案是正确的。但在检查这种情况之前,请检查您的 xaml 是否正确,如其他答案中所述。否则,您可能会花大量时间查看 ItemSource 等,最终发现它是由一个小错字引起的。
    【解决方案3】:

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

       <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>
    

    错误?初始打开&lt;ItemsControl&gt; 标记之后的额外>&lt; 已应用于内置的 Items 集合。稍后设置 DataContext 时,即时 crashola。因此,在调试此问题时,不仅要注意围绕您的 ItemsControl 特定数据子项的错误。

    【讨论】:

    • 同样的事情发生在我身上:额外的&gt; => 异常
    • 当然不仅仅是 > 会这样做。任何不小心输入的字符都会自己变成物品。您可以通过暂时删除您的 ItemsSource 属性来检查这种情况。如果数据网格中仍有行,则需要检查无关字符
    • Armentage...你刚刚救了我我不知道找了多少小时!!!非常感谢您发布这个...投票!
    • 非常有趣。我不确定为什么这不是编译错误。它也吸引了我!
    • 天哪,我遇到了同样的错误:Extra ">"。我可以给你买啤酒吗?多么奇怪的错误,如果没有编译错误很难找到!这拯救了我的一天!
    【解决方案4】:

    我也在不同的场景中。

    <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>
    

    现在,当您完成缺少的标签 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>
    

    【讨论】:

    • 为什么 WPF 必须如此不明显?为 ListBox 设置 DataTemplate 会导致有趣的异常,但它们都没有导致正确的方向。
    • 当我使用&lt;ItemsControl&gt; 时,这已解决。
    【解决方案5】:

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

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

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

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

    【讨论】:

    • 这就是解决我的问题的原因!
    • 找不到ItemsControl
    【解决方案6】:

    ⚠️ 以不同的方式陈述答案 ⚠️

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

    例如

    这是失败的:

    下面的ItemsPanelTemplate 子节点没有正确的 父节点

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

    这是有效的:

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

    ? 提供了&lt;ItemsControl.ItemsPanel&gt; 的正确父节点^^^。 ?

    【讨论】:

    • 这个。缺少&lt;DataGrid.Columns&gt; 并且在&lt;DataGrid&gt; 中直接有模板列。奇怪的错误。
    • 这个也是我的,错误是完全错误的,感谢你解决这个问题!
    【解决方案7】:

    例外

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

    当您通过不同来源将项目添加到ItemsSource 时会发生此异常。所以 确保您没有意外遗漏标签、放错标签、添加额外标签或误写标签。

    <!--Right-->
    
    <ItemsControl ItemsSource="{Binding MyItems}">
         <ItemsControl.ItemsPanel.../>
         <ItemsControl.MyAttachedProperty.../>
         <FrameworkElement.ActualWidth.../>
    </ItemsControl>
    
    
    <!--WRONG-->
    
    <ItemsControl ItemsSource="{Binding MyItems}">
         <Grid.../>
         <Button.../>
         <DataTemplate.../>
         <Heigth.../>
    </ItemsControl>
    

    虽然ItemsControl.ItemsSource 已通过Binding 设置,但无法将其他项目(网格、按钮...)添加到源中。 然而,虽然ItemsSource未使用,但允许以下代码:

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

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

    【讨论】:

    • 您在此处所说的某些内容促使我仔细查看了我的数据网格列...然后我意识到它们不在 datagrid.columns 标记中。 +1 让我在精神上慢跑。
    【解决方案8】:

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

    参考:DataGridTemplateColumn : Items collection must be empty before using ItemsSource.

    【讨论】:

      【解决方案9】:

      在我的例子中,它只是 ListView 中的一个额外的 StackPanel:

      <ListView Name="_details" Margin="50,0,50,0">
                  <StackPanel Orientation="Vertical">
                      <StackPanel Orientation="Vertical">
                          <TextBlock Text="{Binding Location.LicenseName, StringFormat='Location: {0}'}"/>
                          <TextBlock Text="{Binding Ticket.Employee.s_name, StringFormat='Served by: {0}'}"/>
                          <TextBlock Text="{Binding Ticket.dt_create_time, StringFormat='Started at: {0}'}"/>
                          <Line StrokeThickness="2" Stroke="Gray" Stretch="Fill" Margin="0,5,0,5" />
                          <ItemsControl ItemsSource="{Binding Items}"/>
                      </StackPanel>
                  </StackPanel>
              </ListView>
      

      变成:

      <ListView Name="_details" Margin="50,0,50,0">
                      <StackPanel Orientation="Vertical">
                          <TextBlock Text="{Binding Location.LicenseName, StringFormat='Location: {0}'}"/>
                          <TextBlock Text="{Binding Ticket.Employee.s_name, StringFormat='Served by: {0}'}"/>
                          <TextBlock Text="{Binding Ticket.dt_create_time, StringFormat='Started at: {0}'}"/>
                          <Line StrokeThickness="2" Stroke="Gray" Stretch="Fill" Margin="0,5,0,5" />
                          <ItemsControl ItemsSource="{Binding Items}"/>
                      </StackPanel>
              </ListView>
      

      一切都很好。

      【讨论】:

        【解决方案10】:

        在我的例子中,它没有为 ItemsControl 使用 DataTemplate。

        旧:

        <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>
        

        新:

        <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>
        

        【讨论】:

        • 我应该感谢你 4 个小时,我花时间试图解决这个烂摊子......谢谢
        【解决方案11】:

        我的是数据网格样式。如果您忽略样式周围的&lt;DataGrid.RowStyle&gt; 标签,您就会遇到问题。奇怪的是它像那样工作了一段时间。这是错误的代码。

         <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>
        

        好的

         <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>
        

        【讨论】:

          【解决方案12】:

          我有同样的错误。问题是在标签 和 之间错误添加了这个额外的符号“>”:

          <ComboBox 
             ItemsSource="{Binding StatusTypes}"
             DisplayMemberPath="StatusName"
             SelectedValuePath="StatusID">
             <ComboBox.SelectedValue>
                <Binding Path="StatusID"/>
             </ComboBox.SelectedValue>
             >
          </ComboBox>
          

          这是正确的代码:

          <ComboBox 
             ItemsSource="{Binding StatusTypes}"
             DisplayMemberPath="StatusName"
             SelectedValuePath="StatusID">
             <ComboBox.SelectedValue>
                <Binding Path="StatusID"/>
             </ComboBox.SelectedValue>
          </ComboBox>
          

          【讨论】:

            【解决方案13】:

            当我尝试将上下文菜单应用到我的TreeView 时,我遇到了这个错误。这些尝试最终导致了一个错误的 XAML,它以某种方式编译:

            <TreeView Height="Auto" MinHeight="100"  ItemsSource="{Binding Path=TreeNodes, Mode=TwoWay}" 
                ContextMenu="{Binding Converter={StaticResource ContextMenuConverter}}">
                ContextMenu="">
                <TreeView.ItemContainerStyle>
                ...  
            

            注意有问题的行:ContextMenu=""&gt;
            我不知道它为什么编译,但我认为值得一提的是这个神秘异常消息的原因。正如 Armentage 所说,仔细查看 XAML,尤其是在您最近编辑过的地方。

            【讨论】:

              【解决方案14】:

              我在另一种情况下遇到了这个错误。我尝试直接在 &lt;TreeView&gt; 中为 TreeViewItems 定义样式,但应该将其嵌入在 &lt;TreeView.ItemContainerStyle&gt; 中。

              错误:

              <TreeView ItemsSource="{Binding ExampleListView}">
                  <Style TargetType="{x:Type TreeViewItem}">
                      <Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}"/>
                      <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}"/>
                  </Style>
                  <TreeView.ItemTemplate>
                      <HierarchicalDataTemplate ItemsSource="{Binding SubItemListList}">
                      ...
                      </HierarchicalDataTemplate>
                  </TreeView.ItemTemplate>
              </TreeView>
              

              正确:

              <TreeView ItemsSource="{Binding ExampleListView}">
                  <TreeView.ItemContainerStyle>
                      <Style TargetType="TreeViewItem">
                          <Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}"/>
                          <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}"/>
                      </Style>
                  </TreeView.ItemContainerStyle>
                  <TreeView.ItemTemplate>
                      <HierarchicalDataTemplate ItemsSource="{Binding SubItemListList}">
                      ...
                      </HierarchicalDataTemplate>
                  </TreeView.ItemTemplate>
              </TreeView>
              

              【讨论】:

                【解决方案15】:

                我遇到了这个问题,因为我的 XAML 中缺少一个级别的标记 &lt;ListView.View&gt;

                这段代码产生了这个错误。

                <Grid>
                    <ListView Margin="10" Name="lvDataBinding" >
                        <GridView>
                            <GridViewColumn Header="Name" Width="120" DisplayMemberBinding="{Binding Name}" />
                            <GridViewColumn Header="Age" Width="50" DisplayMemberBinding="{Binding Age}" />
                            <GridViewColumn Header="Mail" Width="150" DisplayMemberBinding="{Binding Mail}" />
                        </GridView>
                    </ListView>
                </Grid>
                

                以下修复了它

                <Grid>
                    <ListView Margin="10" Name="lvDataBinding" >
                        <ListView.View> <!-- This was missing in top! -->
                            <GridView>
                                <GridViewColumn Header="Name" Width="120" DisplayMemberBinding="{Binding Name}" />
                                <GridViewColumn Header="Age" Width="50" DisplayMemberBinding="{Binding Age}" />
                                <GridViewColumn Header="Mail" Width="150" DisplayMemberBinding="{Binding Mail}" />
                            </GridView>
                        </ListView.View>
                    </ListView>
                </Grid>
                

                【讨论】:

                  【解决方案16】:

                  也许不是一个有用的答案,但我在更改列顺序时遇到了同样的问题,并犯了如下示例中的错误。有很多列,我对它们进行了重新排序,并以某种方式在结束标记 /DataGrid.Columns 之后粘贴了一个:

                         <DataGridTemplateColumn x:Name="addedDateColumn" Header="Added Date" Width="SizeToHeader">
                                  <DataGridTemplateColumn.CellTemplate>
                                      <DataTemplate>
                                          <TextBlock Text="{Binding Path=AddedDate}" />
                                      </DataTemplate>
                                  </DataGridTemplateColumn.CellTemplate>
                              </DataGridTemplateColumn>
                          </DataGrid.Columns>
                              <DataGridTemplateColumn x:Name="rowguidColumn" Header="rowguid" Width="SizeToHeader">
                                  <DataGridTemplateColumn.CellTemplate>
                                      <DataTemplate>
                                          <TextBlock Text="{Binding Path=rowguid}" />
                                      </DataTemplate>
                                  </DataGridTemplateColumn.CellTemplate>
                              </DataGridTemplateColumn>
                      </DataGrid>
                  

                  反正就是因为这个耽误了半个小时。希望这对其他人有帮助。

                  【讨论】:

                    【解决方案17】:

                    注意错别字!我有以下

                    <TreeView ItemsSource="{Binding MyCollection}">
                        <TreeView.Resources>
                            ...
                        </TreeView.Resouces>>
                    </TreeView>
                    

                    (注意拖尾 >,它被解释为内容,所以你设置了两倍的内容......花了我一段时间 :)

                    【讨论】:

                    • Armentage 已经提到了这一点,还有一点解释。
                    【解决方案18】:

                    我遇到了同样的错误。
                    就我而言,我只是删除了一行&lt;UniformGrid Columns="3" /&gt;

                    <ListBox>
                        <UniformGrid Columns="3" /> // remove this line!!!!
                        ...
                    </ListBox>
                    

                    【讨论】:

                      猜你喜欢
                      • 2012-07-24
                      • 1970-01-01
                      • 2012-03-04
                      • 2013-08-08
                      • 2012-08-02
                      • 2014-01-07
                      • 1970-01-01
                      • 2010-12-08
                      • 2023-03-11
                      相关资源
                      最近更新 更多