I have a UI with nested WPF UserControls each with their own view models. A simple case of the view (XAML) hierarchy would be:
MainWindow
|-> Logical group
|-> Logical control
|-> Second logical group
|-> Third logical group
|-> Logical control
Each XAML view has a ViewModel which encapsulates the interaction logic. My questions is about communicating ViewModel state from a parent view model to the child view models.
For example, a user interaction in the MainWindow could set a CurrentlySelectedGroup variable in the MainWindowViewModel. I need to know what that value is inside of the LogicalControlViewModel.
There are two main ways I’m considering to do this. First, I could broadcast an event DispatchGroupSelected and then assign a delegate inside LogicalControlViewModel as a listener to that event. Second, I could Bind to the CurrentlySelectedGroup property of MainWindowViewModel inside of LogicalControlViewModel.
My first instinct is to use events to communicate between parent and child view models. I think binding is best kept between a View Model and its View. Events up until now have been used to communicate between my ViewModel and Commands. If there is another possible direction to take that would be better I’d be interested to hear about it.
Have you tryed with a message bus?? there are several frameworks out there that implements this pattern:
Using this pattern your ViewModels can comunicate with the others in a loosely coupled way, because every ViewModel just sends a message and don’t care who is going to listen for it. And if a ViewModel wants to listen for a specific message type it can subscribe to get only those messages.