【问题标题】:ObservableCollection is not providing adding new row to the datagrid?ObservableCollection 不提供向数据网格添加新行?
【发布时间】:2012-12-25 07:51:07
【问题描述】:

这是我的第一个 WPF 应用程序,我需要一些帮助 我创建了一个 WPF 窗口,其中包含使用 EF 绑定到数据库的 Datagrid,CollectionViewSource 当从 Data Sources Window 拖放表到 Window 上时 MDI 自动生成代码

ObjectQuery<ITPORTAL.HRMS_IT_ASSET_MASTER> ass = gRACHRMSEntities.HRMS_IT_ASSET_MASTER;

并将对象查询分配给 CollectionViewSource.Source 如下

hRMS_IT_ASSET_MASTERQuery = Load_Asset_Master_Data(gRACHRMSEntities.HRMS_IT_ASSET_MASTER);
hRMS_IT_ASSET_MASTERViewSource.Source = hRMS_IT_ASSET_MASTERQuery.Execute(System.Data.Objects.MergeOption.AppendOnly);

但是这段代码不支持过滤工具,所以我添加了这样的东西

 private ObservableCollection<ITPORTAL.HRMS_IT_ASSET_MASTER> Load_Asset_Master_Data(System.Data.Objects.ObjectQuery<ITPORTAL.HRMS_IT_ASSET_MASTER> objectSet)
        {
            ObservableCollection<ITPORTAL.HRMS_IT_ASSET_MASTER> oc = null;
            try
            {
                var value = from Asset_Master in objectSet
                            where Asset_Master.IT_ASSET_IS_ACTIVE == "1" && Asset_Master.IT_ASSET_IS_SCRAPED == "0" && Asset_Master.IT_ASSET_IS_SCRAP_FINAL == "0"
                            select Asset_Master;
                oc = new ObservableCollection<HRMS_IT_ASSET_MASTER>(value.ToList());
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message, "IT Portal Error", MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK);
            }
            return oc;
        }

并分配给 CollectionViewSource 如下

hRMS_IT_ASSET_MASTERViewSource.Source = Load_Asset_Master_Data(gRACHRMSEntities.HRMS_IT_ASSET_MASTER); 

通过这种方式我可以进行过滤 但我失去了一项功能,因为 当我填充数据网格末尾的行并按保存时 保存命令不考虑添加的行, 保存命令仅响应编辑操作 这是 Save 事件处理程序

private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            try
            {                                               
                if (gRACHRMSEntities.SaveChanges() > 0)
                {
                    txtblkStatus.Text = "Changes has been saved.";                
                }
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK);

        }       }

我在网上查了一下,发现 使用ObservableCollection&lt;T&gt; 时,我必须为IEditableObject 提供我自己的T 实现。

【问题讨论】:

    标签: c# wpf observablecollection


    【解决方案1】:

    我觉得你应该写

    hRMS_IT_ASSET_MASTERViewSource.ItemsSource =Load_Asset_Mast ...
    

    代替:

    hRMS_IT_ASSET_MASTERViewSource.Source =Load_Asset_Mast ...
    

    我的意思是你应该设置 ItemsSource 。

    【讨论】:

      猜你喜欢
      • 2015-10-07
      • 2013-12-21
      • 1970-01-01
      • 2016-05-04
      • 2018-07-05
      • 2013-07-02
      • 2011-01-25
      • 2019-11-14
      • 1970-01-01
      相关资源
      最近更新 更多