加载第二次时,ObservableCollection抛出异常

时间:2017-05-18 11:01:19

标签: c# wpf combobox observablecollection

我有一个ObservableCollection,当我将数据加载到它一次时 当我再次加载时,它会在参考

上设置一个异常
using (PricingManagerEntities db = new PricingManagerEntities())
                    {
                        m_PricingSheetManagerViewModel.Groups = new ObservableCollection<sp_GetGroups_Result>(db.sp_GetGroups(null, true));
                    }
                    return m_PricingSheetManagerViewModel;

我做了以下事情:

  1. 将线条划分为锯齿线:

    var a = db.sp_GetGroups(null, true).ToList();
    b = new ObservableCollection<sp_GetGroups_Result>(a);
    m_PricingSheetManagerViewModel.Groups = b;
    

    并注意到它抛出时: m_PricingSheetManagerViewModel.Groups = b;

  2. 我试图清除群组尝试删除项目,但我总是得到 System.NullReferenceException

    我第一次初始化组时,组为空,并获得2条记录 然后我通过组合框选择其中一组 然后退出窗口,然后我再次进入,它就会抛出我。

    这里是组合框xaml:

    <ComboBox HorizontalAlignment="Left" Width="200"  Name="cmbGroups" ItemsSource="{Binding Groups}" Height="30" DisplayMemberPath="GroupName" SelectionChanged="cmbGroup_changed" HorizontalContentAlignment="Center" Margin="5"/>
    

    选择更改时

    private void cmbGroup_changed(object sender, SelectionChangedEventArgs e)
        {
            long groupID = ((sender as ComboBox).SelectedValue as sp_GetGroups_Result).GroupID;
            m_engine.GetItemsByGroupID(groupID);
        }
    internal void GetItemsByGroupID(long groupID)
        {
            if (m_PricingSheetManagerViewModel.Items == null)
                m_PricingSheetManagerViewModel.Items = new ObservableCollection<sp_GetItems_Result>();
    
            m_PricingSheetManagerViewModel.Items.Clear();
            using (PricingManagerEntities db = new PricingManagerEntities())
            {
                List<ItemsInGroups> groups = db.ItemsInGroups.Where(iig => iig.GroupID == groupID).ToList();
                foreach(ItemsInGroups group in groups)
                {
                    var temp = db.sp_GetItems(group.ItemID, true).FirstOrDefault();
                    if(temp != null)
                        m_PricingSheetManagerViewModel.Items.Add(temp);
                }
            }
        }
    

0 个答案:

没有答案