Why two Models should not talk to each othetr
Well , In MVVM pattern it is good practice that two models should not know or talk with each other. That means you should not create a 开发者_C百科object of one model in other and then register for event or performing similar things.
But why, what is wrong if two models know each other. I am writing the code and what will happen if both my models know each other.
If you are going to circumvent MVVM in any way you want to have a good reason (otherwise you might as well just write it as traditional code-behind and save some typing) :)
There are several benefits of using MVVM, which are mainly to do with very loose coupling, unit testing and reuse.
The basic principal of loose coupling goes something like this:
- A View knows how to display data of a certain shape, but has no idea where the data comes from.
- A ViewModel provides a certain shape of data and settings, that views can use, but has no idea who is displaying it.
- A Model knows how to hold generic data, but no idea who is consuming it
- A Controller (missing from most MVVM explanations) decides what data to fetch, what data to display and where to display it. This is where the decision making belongs.
If you require your ViewModels to know about each other, then you are most likely missing a Controller object that manages your 2 ViewModels and associated Models/Views.
If you can provide more information about why your models are currently linked, I may be able to suggest an alternative.
It's often perfectly appropriate for view models to interoperate with each other. Parent/child relationships in the view involve the parent view model holding a collection of child view models, after all. There are any number of circumstances in which, for instance, the availability of commands in the parent view depend on the state of its children. It's sometimes appropriate to delegate this to a separate controller class, but it's also often not worth the effort to do this.
It really depends on the overall complexity of your application. Sometimes that kind of effort is essential; sometimes it's just gold-plating.
精彩评论