Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF MVVM: How do ViewModels communicate with each other?

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?

like image 291
Dev1 Avatar asked Feb 03 '11 22:02

Dev1


1 Answers

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.

like image 118
Daniel Auger Avatar answered Oct 19 '22 14:10

Daniel Auger