WPF How to call some logic in a parent ViewModel from a child ViewModel in MVVM

5.7k views Asked by At

I'm using Prism. I have a tabcontrol in my parent View. I have two tabs in my tab control. Each tab has a different View. Each tab has a button which may or may not (depending on some internal logic) cause the tabcontrol to switch to a different tab. What is the best practice for setting up an architecture like this?

I am against using the EventAggregator because I believe its sloppy and is easy to misuse. Is there another way to do this? Should I use a RoutedCommand or events?

I'm also going to be sharing information between the tabs, but I want them to be loosely coupled and have distinct ViewModels. Any thoughts, suggestions, or criticism?

Thanks! Brett

2

There are 2 answers

0
Robert Rossney On BEST ANSWER

My first preference, generally, is to have the child view model raise an event, and for the parent to set its handler when it creates the child.

But there are scores of ways to do this sort of thing. For instance, if all of the tab-switching logic lived in the parent, you could create a command on the parent and bind the button to it using AncestorType binding. Then you don't have to touch the child view model at all.

0
Matt Hamilton On

I wrote a blog post a while back outlining some of the options for child-to-parent ViewModel communication. Might give you some ideas.

Nested ViewModels