![](/img/trans.png)
[英]How to update list<> from another View model on same View in WPF using Caliburn.Micro MVVM?
[英]WPF MVVM Update Model Using View Model
我有一個像這樣的樹結構:
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
ObservableCollection
從NodeViewModel
也是Children
List<Node>
從Node
類。
如果僅更新模型,則由於未調用NotifyPropertyChanged
而不會更新UI,並且如果僅更新視圖,則更改將丟失,因為吸氣劑將創建另一個ObservableCollection
,並且更改也不會反映在模型上。
如何通過視圖模型類更新模型?
無論采用哪種方式對其進行切片,視圖模型都需要完全封裝該模型。 如果您具有“保存”命令,則可以在那時更新/重新創建模型的集合。
假設您沒有“保存”命令,並且該模型應始終反映視圖模型的當前狀態,則一個選項是訂閱ObservableCollection<T>.CollectionChanged
事件並動態更新基礎集合。
附帶一提,您很可能也不想在每次調用Children_get
都創建一個新集合,最好是懶加載您保留的那個。
ObservableCollection已經實現INotifyPropertyChanged。 但是,只有在集合計數發生更改時,它才起作用。 另外,為什么要ViewView集合? 但我認為您正在尋找此實現:
private ObservableCollection<Node> _children;
public ObservableCollection<Node> Children {
...code logic
}
不要忘記處理更改的事件
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.