WPF MVVM: How do ViewModels communicate with each other?

喜你入骨 提交于 2020-01-20 14:21:48

问题


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?


回答1:


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.




回答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.



来源:https://stackoverflow.com/questions/4892731/wpf-mvvm-how-do-viewmodels-communicate-with-each-other

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!