我有一个像这样的树结构:

public class Node
{
    public Node Parent { get; set; }
    public List<Node> Children { get; set; }
    public NodeValue Item { get; set; }
}

和这样的NodeViewModel:
    public class NodeViewModel : INotifyPropertyChanged
    {
    public Node Node
    {
        get;
        private set;
    }
     public NodeViewModel(Node node)
    {
      this.Node = node;
      this._children = new ObservableCollection<NodeViewModel>();
    }

  public string Code {
      get
      {
          return this.Item.Code;
      }
      set
      {
          this.Item.Code = value;
          NotifyPropertyChanged("Code");
      }
           }

  public Node Parent
  {
      get
      {
          return this.Node.Parent;
      }
      set
      {
          if (value != this.Node.Parent)
          {
              this.Node.Parent = value;
              NotifyPropertyChanged("Parent");
          }
      }
  }

  public NodeValue Item
  {
      get
      {
          return Node.Item;
      }
      set
      {
          this.Node.Item = Item;
      }
  }
private ObservableCollection<NodeViewModel> _children;

public ObservableCollection<NodeViewModel> Children
  {
      get
      {
          _children.Clear();
         foreach(var child in Node.Children)
         {
             _children.Add(new NodeViewModel(child));
         }
         return _children;
      }
      protected set
      {
          this._children = value;
          NotifyPropertyChanged("Children");
      }
  }

问题是最后一个属性,因为当我想使用 View 模型更新模型时,例如,当我想添加新节点时,必须从_children更新ObservableCollection NodeViewModel,还要从Children类更新List<Node> Node

如果仅更新模型,则由于未调用NotifyPropertyChanged而不会更新UI,并且如果仅更新 View ,则更改将丢失,因为getter将创建另一个ObservableCollection,并且更改也不会反射(reflect)在模型上。

如何通过 View 模型类更新模型?

最佳答案

无论采用哪种方式对其进行切片, View 模型都需要完全封装该模型。如果您具有“保存”命令,则可以在那时更新/重新创建模型的集合。

假设您没有“保存”命令,并且模型应始终反射(reflect) View 模型的当前状态,则一个选项是订阅ObservableCollection<T>.CollectionChanged事件并动态更新基础集合。

附带一提,您很可能也不想在每次调用Children_get时都创建一个新的集合,最好只延迟加载一个您所保持的集合。

关于c# - 使用 View 模型的WPF MVVM更新模型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28361117/

10-17 02:34