开发者

Clarification of MVVM - interactions between views

开发者 https://www.devze.com 2023-03-13 07:11 出处:网络
I\'m using WPF and trying to program the M开发者_StackOverflowVVM way. I understand how every view has its own view model and this works quite well.I am struggling to manage the interaction between v

I'm using WPF and trying to program the M开发者_StackOverflowVVM way.

I understand how every view has its own view model and this works quite well. I am struggling to manage the interaction between views though.

Say I have two views, View1 and View2, each with its own ViewModel, ViewModel1 and ViewModel2. If I have a combobox on View1 and a button, what is the correct way to close the first view, notify the second view of the selection and show the second view once the button is pressed? It doesn't seem like it should go in the model because it's a UI thing. The ViewModel shouldn't know how to open and close WPF forms (or should it?) And the views shouldn't know about any other ViewModels (or should they?)

So how are these problems solved? In a nutshell:

1) How is data passed between views?

2) What manages the lifetime/visibility of views?


It will depend on whether you are doing view model or view first, and the exact implementation details will depend on if you are using an MVVM framework. If you aren't using a framework, then I would strongly recommend you start using one.

In your example, when the button is pressed, a method on ViewModel1 will be invoked. If doing view model first (which I would recommend), you would instantiate an instance of ViewModel2, and at this point you could pass in the combobox selection to the constructor of ViewModel2.

Depending on your framework, there will be different ways of then displaying the view associated with ViewModel2.


For 1) you can sychronize data through the DataModel. Provided each view shares the same instance of the DataModel and it implements INotifyPropertyChanged multiple views can be updated simulateneously.

Your sesond question is a matter of design, as @devdigital states it can depend on whether it is View first or ViewModel first. I would consider the introduction of a Controller class in much as the same way ASP.Net MVC works which controls which view is displayed. You can expose a ViewClosed event on the ViewModel which the controller can listen to and based on your workflow open another view.


You might consider introducing Controllers which are responsible for the lifetime management of the ViewModels. Furthermore, they mediate between the ViewModels.

The sample applications of the WPF Application Framework (WAF) show how these Controllers can be implemented.

0

精彩评论

暂无评论...
验证码 换一张
取 消