I am currently designing simple editor as part of learning process. Its basicaly hierarchical tree structure of polygons-lines-points, that is implemented in data model. I need to display these data in two views
First view: hierarchical data in tree view item Second view: rendered geometry on screen
Following the MVVM pattern i have implemented model view classes around data model ( point model view, line model view, etc.. ) . In tree view I am using hierarchical data templates to properly display specific data. On second view I need to render current state of geometry, currently its just one model-view wrapper around polygon data class, that travels all children and render them in onRender method. In this case I am using multiple view models over the same data, both for quite different purpose.
There is a problem when I make some modification in tree view model (adding points for example) , resulting in change of underlying data model. However second view model does not directly observe data in model view, it updates render view only if I make modification trough its modelview clas. Is there some elegant solution to update both view models concurently ?
I solved this by introducing a Presenter. Here's basically how it works:
That keeps them all in sync without any ViewModel having to know about any other ViewModels. All of my Hierarchical ViewModels implement an interface IViewModelWithChildren
, which exposes an IEnumerable<IViewModel>
property, which lets the Presenter walk any given ViewModel tree and notify all of them, as long as it has a reference to the root ViewModel.
I also like it because it funnels all user actions through a single point (the Presenter callback) and I can inject certain concerns there. For instance, if an unhandled exception happens in the Model logic, I can catch it at that point and instantiate a nice MessageViewModel to display to the user.
If you must use different viewmodels for the two views, you can have the viewmodel for the geometry view subscribe to PropertyChanged
on the hierarchical viewmodel, or you can expose a different event for this. That way, the geometry view model will know to look again at the underlying model and update itself.
If you want it further decoupled, you can use an event aggregator, as available in the Prism project.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.