【问题标题】:Getting an "Items collection must be empty before using ItemsSource" with EF使用 EF 获取“使用 ItemsSource 之前必须为空的项目集合”
【发布时间】:2013-05-12 22:25:37
【问题描述】:

我们正在使用实体框架来检索我们的数据。我们正在尝试将集合视图源绑定到组合框以显示数据。下面是 CollectionViewSource 的定义:

<CollectionViewSource x:Key="aSICodesControlledEnvironmentViewSource" d:DesignSource="{d:DesignInstance {x:Type AsiEF:ASICodesControlledEnvironment}, CreateList=True}">

AsiEF 是实体框架程序集。这是组合框的 XAML:

<ComboBox x:Name="cmbControlledEnvLast30" Margin="480,20,0,0" DisplayMemberPath="ContEnvDesc"  SelectedValue="ContEnvDesc"  Width="150"  FontSize="14" 
      ItemsSource="{Binding Source={StaticResource aSICodesControlledEnvironmentViewSource}}">
<CollectionViewSource>
    <CollectionViewSource.SortDescriptions>
        <scm:SortDescription PropertyName="DisplayOrder" />
    </CollectionViewSource.SortDescriptions>
</CollectionViewSource>
</ComboBox>

如您所见,我们正在尝试按字段 DisplayOrder 对数据进行排序,即使该字段在组合框中不可见,我仍然认为 CollectionViewSource 应该能够按该字段对数据进行排序字段。

但这失败的地方在于尝试检索数据并将其分配给用户控件的加载事件中的集合视图源的源:

ComboBoxSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("aSICodesControlledEnvironmentViewSource")));
ComboBoxSource.Source = asiContext.ASICodesControlledEnvironments;

当试图分配 CollectionViewSource 对象 ComboBoxSource 的 Source 属性时,它挂在第二行。 asiContext 是我们 AsiEF 的 ObjectContext。引发的错误是“在使用 ItemsSource 之前,Items 集合必须为空”。对不起,我不明白我们做错了什么。我尝试从 XAML 中删除 ItemsSource 的 ComboBox 中的分配,但这不起作用。那么,我们哪里出错了?

【问题讨论】:

    标签: wpf entity-framework collectionviewsource


    【解决方案1】:

    我认为你应该在CollectionViewSource 定义中声明SortDescriptions

    <CollectionViewSource x:Key="aSICodesControlledEnvironmentViewSource"
                          d:DesignSource="{d:DesignInstance {x:Type AsiEF:ASICodesControlledEnvironment}, CreateList=True}">
        <CollectionViewSource.SortDescriptions>
            <scm:SortDescription PropertyName="DisplayOrder" />
        </CollectionViewSource.SortDescriptions>
    </CollectionViewSource>
    

    并从ComboBox 中删除额外的CollectionViewSource。这将被解释为ComboBox.Items,稍后当ComboBox.ItemsSource 绑定时,它会抛出异常。

    <ComboBox x:Name="cmbControlledEnvLast30"
              ItemsSource="{Binding Source={StaticResource aSICodesControlledEnvironmentViewSource}}">
    
    </ComboBox>
    

    【讨论】:

    • 我刚刚按照您的建议进行操作,但收到错误消息“'System.Windows.Data.BindingListCollectionView' 视图不支持排序。”在 Loaded 事件中分配 ComboBoxSource 的 Source 属性时出现错误。
    • 对不起。我对此一无所知,因为 BindingListCollectionView 确实支持排序。见here
    • 感谢 LPL 的链接。我明白你的意思,BindingListCollectionView 确实支持排序。我到达这里,但可能是因为数据源来自 EF 吗?对来自 EF 的集合进行排序的唯一方法是使用 LINQ 表达式吗?我们宁愿使用 XAML。
    • 也许这个链接可以帮助你:Entity Framework 4.0 Databinding with sorting not working.
    • 谢谢你,LPL,我认为这确实解决了这个问题。
    猜你喜欢
    • 2012-07-24
    • 2010-10-15
    • 1970-01-01
    • 2012-03-04
    • 2013-08-08
    • 2012-08-02
    • 2014-01-07
    • 1970-01-01
    • 2010-12-08
    相关资源
    最近更新 更多