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?

ASh
  • 34,632
  • 9
  • 60
  • 82
Dev1
  • 193
  • 1
  • 5
  • 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 03 '11 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 03 '11 at 23:22

2 Answers2

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.

Daniel Auger
  • 12,535
  • 5
  • 52
  • 73
  • *I generally favor composition over inheritance in my ViewModels* - they are two different things and a VM can use both. – slugster Feb 04 '11 at 12:07
  • @slugster - Yup, I use both. Example: I often put a lot of the infrastructure concerns in a base ViewModel (INotifyPropertyChanged etc...). – Daniel Auger Feb 04 '11 at 16:29
  • @slug I'd say inheritance for functionality and composition for information. – LuckyLikey Apr 21 '17 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.

Appulus
  • 18,630
  • 11
  • 38
  • 46
H H
  • 263,252
  • 30
  • 330
  • 514