UserControls in the View
I want to change a WPF projec开发者_高级运维t into MVVM pattern. I would like to have 2 usercontrols in view so I can reuse them later. If my mainwindow is the view with 2 usercontrols layed out in a dockpanel, do I need to have 2 viewmodels? Also what would be the right way to setup the usercontrols? Thanks in advance!!!
You could have one ViewModel, two ViewModels, or many, many ViewModels. You can think of the ViewModels as representing some kind of logical object or the data underlying a screen, or something that should be processed, serialised or cached separately.. it doesn't matter so long as you put a little thought into it.
A good starting point would be to consider what you are displaying/editing/working with. If the two UCs are views on the same data (for instance, like a code editor/preview window), you might have one ViewModel. If the two UCs are showing completely separate data, you might have two. If one of the UCs has 5 tab pages and shows lots of different data, it should probably bind to more than one.
If you can give a little more information about what you're doing, we can give an answer. As it stands any answer that gives an exact number based on your current question will be jumping the gun.
If they are different, then yes you should have a ViewModel for each. If they are clones, then they need only one ViewModel. This article is a fantastic resource for learning the MVVM pattern. It is a bit old, but it covers the pattern very nicely for beginners. I have been using it myself over the last few weeks.
Well, since you're going to be reusing the user controls elsewhere then they should each have a viewmodel associated with them. This way when it's time to re-use them, you don't have to rewrite the code again.
This really depends on you usercontrols, but it is possible to have only one viewmodel fo the containing view, and simply bind properties from it to specific properties on the usercontrols
精彩评论