MVVM 同步集合 [英] MVVM Sync Collections

查看:12
本文介绍了MVVM 同步集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C# 和 WPF 中,是否有一种标准化的方法可以将 Model 对象的集合与匹配的 ModelView 对象的集合同步?假设我只有几个苹果并且我可以将它们全部保存在内存中,我正在寻找某种可以使以下两个集合保持同步的类.

Is there a standardized way to sync a collection of Model objects with a collection of matching ModelView objects in C# and WPF? I'm looking for some kind of class that would keep the following two collections synced up assuming I only have a few apples and I can keep them all in memory.

另一种说法,我想确保如果我将 Apple 添加到 Apples 集合中,我希望将 AppleModelView 添加到 AppleModelViews 集合中.我可以通过监听每个集合的 CollectionChanged 事件来编写我自己的.这似乎是一个比我更聪明的人定义了正确的方法"来做到这一点的常见情况.

Another way to say it, I want to make sure if I add an Apple to the Apples collection I would like to have an AppleModelView added to the AppleModelViews collection. I could write my own by listening to each collections' CollectionChanged event. This seems like a common scenario that someone smarter than me has defined "the right way" to do it.

public class BasketModel
{
    public ObservableCollection<Apple> Apples { get; }
}

public class BasketModelView
{
    public ObservableCollection<AppleModelView> AppleModelViews { get; }
}

推荐答案

我可能不完全理解您的要求,但是我处理类似情况的方法是在 ObservableCollection 上使用 CollectionChanged 事件,然后简单地根据需要创建/销毁视图模型.

I may not exactly understand your requirements however the way I have handled a similar situation is to use CollectionChanged event on the ObservableCollection and simply create/destroy the view models as required.

void OnApplesCollection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{    
  // Only add/remove items if already populated. 
  if (!IsPopulated)
    return;

  Apple apple;

  switch (e.Action)
  {
    case NotifyCollectionChangedAction.Add:
      apple = e.NewItems[0] as Apple;
      if (apple != null)
        AddViewModel(asset);
      break;
    case NotifyCollectionChangedAction.Remove:
      apple = e.OldItems[0] as Apple;
      if (apple != null)
        RemoveViewModel(apple);
      break;
  }

}

当您在 ListView 中添加/删除大量项目时,可能会出现一些性能问题.

There can be some performance issues when you add/remove a lot of items in a ListView.

我们通过以下方式解决了这个问题:扩展 ObservableCollection 以具有 AddRange、RemoveRange、BinaryInsert 方法并添加通知其他人集合正在更改的事件.与扩展的 CollectionViewSource 一起,在更改集合时临时断开源连接,它可以很好地工作.

We have solved this by: Extending the ObservableCollection to have an AddRange, RemoveRange, BinaryInsert methods and adding events that notify others the collection is being changed. Together with an extended CollectionViewSource that temporary disconnects the source when the collection is changed it works nicely.

HTH,

丹尼斯

这篇关于MVVM 同步集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆