MVVM in WPF - How to alert ViewModel of changes in Model… or should I?

前端 未结 11 702
离开以前
离开以前 2020-11-27 09:51

I am going through some MVVM articles, primarily this and this.

My specific question is: How do I communicate Model changes from the Model to the ViewModel?<

11条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-27 10:28

    You can raise events from the model, which the viewmodel would need to subscribe to.

    For example, I recently worked on a project for which I had to generate a treeview (naturally, the model had a hierarchical nature to it). In the model I had an observablecollection called ChildElements.

    In the viewmodel, I had stored a reference to the object in the model, and subscribed to the CollectionChanged event of the observablecollection, like so: ModelObject.ChildElements.CollectionChanged += new CollectionChangedEventHandler(insert function reference here)...

    Then your viewmodel gets automatically notified once a change happens in the model. You can follow the same concept using PropertyChanged, but you will need to explicitly raise property change events from your model for that to work.

提交回复
热议问题