19

I have a View which has 2 sub views on it and a ViewModel is assigned to each view:

ViewA - ViewModelA
{ 
   ViewB - ViewModelB
   ViewC - ViewModelC
}

ViewB has a text box and ViewC has a combobox, both of which i need access from ViewModelA. Not the GUI control itself, but the bound value i.e. .Text of the textbox and .SelectedItem of the ComboBox. Currently i just have ViewModelB and ViewModelC as properties on ViewModelA but it feels wrong.

What's the standard way for view models to communicate with each other without breaking the MVVM pattern?

2
  • 2
    ViewModelB has a text box and ViewModelC has a combobox... If I'm to take this literally, you're already breaking the MVVM pattern. ViewModels don't reference WPF controls, they expose properties which are bound to Dependency Properties of controls in the Views. VMs can expose properties for the benefit of Views bound to them, but they should remain ignorant of the nature (or existence) of those Views.
    – Dan J
    Feb 3, 2011 at 23:17
  • 1
    whoops i meant to say ViewB has a text box and ViewC has a combo box, i'll fix it up.
    – Dev1
    Feb 3, 2011 at 23:22

2 Answers 2

12

One way to have disconnected ViewModels communicate to each other is to use a publish / subscribe mechanism such as PRISMs EventAggregator. However, in a parent / child ViewModel relationship, I think it's fine for the parent to have direct knowledge and control over the child ViewModel.

Personally, I don't think composing a ViewModel out of other ViewModels is a bad practice. I do it all the time. I generally favor composition over inheritance in my ViewModels.

3
  • I generally favor composition over inheritance in my ViewModels - they are two different things and a VM can use both.
    – slugster
    Feb 4, 2011 at 12:07
  • @slugster - Yup, I use both. Example: I often put a lot of the infrastructure concerns in a base ViewModel (INotifyPropertyChanged etc...). Feb 4, 2011 at 16:29
  • @slug I'd say inheritance for functionality and composition for information.
    – LuckyLikey
    Apr 21, 2017 at 11:55
2

The ViewModels usually 'inherit' relationships from the Model. And it's not wrong to add a relation when it makes sense.

It's perfectly OK for a ViewModel to have a property referring to another ViewModel.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.