简体   繁体   中英

How to have separate viewmodels for each usercontrol in WPF

I have a MainWindow which consists of several UserControls .

Currently, I have one God ViewModel.cs which is defined at MainWindow level and does the job for all the UserControls.

Now I feel that this is not the right way to do it. Maybe I should have separate viewmodels for each of the user controls, right? But my problem is how to interact between these? Let's say some event happens in usercontrol1 which changes something in usercontrol2 's viewmodel?

You should use events to control interactions between the viewmodels. The problem with using regular .NET events is that it couples the viewmodels, since they would have explicit knowledge of eachother.

To get around this you could use an existing MVVM framework that provides an 'event broker', that is, a mechanism through which viewmodels can subscribe to, and publish events without having to know about eachother.

Examples of MVVM frameworks are PRISM, Caliburn Micro, MVVM Light etc.

You could also roll your own event broker but probably better to go with an existing one unless you have a good reason not to.

There is no definitive answer for this, it depends on the situation. However, some advice for different situations:

  1. If the user controls are just fancy displays for simple data, they probably don't need a view model. The required properties can be exposed via dependency properties and bound to the master view model.

  2. If the user controls are large (and you are using them more like pages) then they would be mostly independent, so interaction is not a concern. If they need to modify some global state, then they could do so in order to update other view models

  3. If there is a lot of interaction, then you likely haven't correctly encapsulated your user controls. In general, I would try to fix that, and if I can't, put shared data in the master view model, and pass that object to the child view models so they can access it.

You also need to be careful with user control view models, if you set the control's DataContext property, your bindings on the user control from the master control will not work as you expect. A simple work around is to use the root UIElement 's DataContext for the child view model.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM