2015-02-06 170 views
1

我有一個樹形結構是這樣的:WPF MVVM更新模型中使用視圖模型

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"); 
     } 
    } 

的問題是最後一個屬性,因爲當我想更新該模型使用視圖模型,例如,當我想添加一個新節點時,我必須更新_children ,從NodeViewModel以及ChildrenList<Node>Node類。

如果我只更新模型的UI不更新,因爲NotifyPropertyChanged未被調用,如果我只更新視圖,更改將會丟失,因爲getter將創建另一個ObservableCollection並且更改不會反映在模型。

如何通過視圖模型類更新模型?

回答

0

無論您如何切片,視圖模型都需要完全封裝模型。如果你有一個「保存」命令,你可以在那個時候更新/重新創建模型的集合。

儘管您沒有「保存」命令,並且模型應始終反映視圖模型的當前狀態,但一種方法是訂閱ObservableCollection<T>.CollectionChanged事件並即時更新基礎集合。


一個側面說明,你最有可能也不想創建一個新的集合,每次Children_get被調用,並且是最好只延遲加載一個你保持周圍。

0

ObservableCollection已經實現了INotifyPropertyChanged。 然而,只有當收集的數量發生變化時,它纔會起作用。 另外你爲什麼要一個ViewModel集合? 但我認爲你正在尋找此實現:

private ObservableCollection<Node> _children; 

public ObservableCollection<Node> Children { 
    ...code logic 
} 

不要忘了處理更改事件