查找 Observable Collection 中更改的项目

Finding the items changed in Observable Collection

我有一个来自 EF 数据库上下文的 class,我已将其显示在基于 ObservableCollection 的数据网格中。用户可以编辑网格,这一切都显示正常。

但是我现在需要将数据发送回数据库。我不想将集合中的所有项目都发送到我的保存方法,所以我可以只找到集合中已更改的项目吗?

您可以使用 NotifyCollectionChangedAction 来检测 ObservableCollection

中哪些项目已被更改

不过,就Jens说了,最好的办法还是让EF帮你处理吧。

干杯。

ObservableCollection<int> listOfObject = new ObservableCollection<int>() { 1, 2, 3, 4};

listOfObject.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(
    delegate (object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {
    if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
        {
            Console.WriteLine($"{e.NewItems[0]} just been added to the list at index = {e.NewStartingIndex}");
        }
        if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Replace)
        {
            Console.WriteLine($"Replace item {e.OldItems[0]} with {e.NewItems[0]}");
        }
    }
);

listOfObject.Add(1);
listOfObject[2] = 3;
listOfObject[3] = 1;

输出:

1 just been added to the list at index = 4

Replace item 3 with 3

Replace item 4 with 1

只是作为一个想法(不是自称这是一个理想的解决方案)我 运行 遇到了类似的问题,四处寻找潜在的解决方案,其中 none 正是我想要的。

我不得不将一个集合传递给 WPF DataGrid,它似乎抱怨使用 List,因此我求助于 ObservableCollection

出于多种原因,我不想直接使用 EF 上下文,主要是因为我想获取项目并将它们传递给中间事务工厂进行处理(业务逻辑)。

因此决定坚持使用 ObservableCollection,而不是对 ViewModel 进行轻微修改,因为我可以自由地这样做。

我的模型最终看起来像这样:

internal class databaseItemModel
{
    int _id; 
    string _description;
    decimal _price; 
    decimal _quantity;
    decimal _cost;
    bool _modified;

    public databaseItemModel()
    {
        _modified = false;
    }

    public int id { get { return _id; } }
    public bool modified { get { return _modified; } }
    public string description { get { return _description; } set { _description = value; _modified = true; } }
    public decimal price { get { return _price; } set { _price = value; _modified = true; } }
    public decimal quantity { get { return _quantity; } set { _quantity = value; _modified = true; } }
    public decimal cost { get { return _cost; } set { _cost = value; _modified = true; } }
    public bool selected { get; set; }

    public void setId(int _idvalue) 
    {
        _id = _idvalue;
    }
    public decimal value
    {
        get { return price * quantity; }
    }
    public void setDescription(string _descr)
    {
        _description = _descr; 
    }
    public void setPrice(decimal _pr)
    {
        _price = _pr;
    }
    public void setQuantity(decimal _qty)
    {
        _quantity = _qty;
    }
    public void setCost(decimal _cst) 
    {
        _cost = _cst;
    }
}

基本上,它背后的简单想法是我会使用函数来填充数据而不是直接使用属性,然后将项目传递给 ObservableCollection,后者将成为 DataGrid.ItemsSource[=11= 的来源]

因为 DataGrid/ObservableCollection 将使用属性 - 修改的对象将被标记为已修改,然后我将能够在退出时获取集合并收集修改的项目。

希望这对您有所帮助。