user1570697
user1570697

Reputation: 83

MVVM-Calling commands on child viewModel

Iam using MVVM and have a main window with Close button and it is bound to the MainWindowViewModel's ICommand command. In the main window there are two UserControl1 and UserControl2 which is bound to viewmodels UserControlVM1 and UserControlVM2 respectively.

UserControlVM1 and UserControlVM2 has command named CleanUp that will clean up the resources.

So Whenever the close button is clicked on the mainwindow, i wanted to call the CleanUp command of Usercontrol viewmodels. How can we do this in XAML or any other alternatives?

Upvotes: 0

Views: 1356

Answers (3)

Arhiman
Arhiman

Reputation: 227

You could inspire yourself from a technique from Prism's developer guide.

In Patterns and Practices' Prism Framework, CompositeCommand allows several ViewModel to register their own command against a single CompositeCommand, so that all can be called with one single call. You'd also need this global class that is referenced in all your ViewModels, but not necessarily a static one since you don't have loose coupled modules.

Upvotes: 0

user1548266
user1548266

Reputation:

A common implementation for communication between ViewModels is the Mediator Pattern which describes an object common between your ViewModels providing a Publish/Subscribe model. When an Event of interest occurs in an object it publishes a notification to the Mediator, one or more objects that are subscribed to that particular Event of the Mediator are then notified of the Event occurring in the original object.

Mediator Pattern Example

Upvotes: 1

devdigital
devdigital

Reputation: 34349

You should consider a view model first approach, in which case the MainWindowViewModel would have references to the UserControlVM1 and UserControlVM2, and can call the CleanUp methods directly.

You should consider using an MVVM framework if you're using MVVM.

Upvotes: 0

Related Questions