我有一個樹形結構是這樣的: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
以及Children
List<Node>
從Node
類。
如果我只更新模型的UI不更新,因爲NotifyPropertyChanged
未被調用,如果我只更新視圖,更改將會丟失,因爲getter將創建另一個ObservableCollection
並且更改不會反映在模型。
如何通過視圖模型類更新模型?