MVVM Mediator multiple instances
Question
Can someone explain how the mediator pattern works with multiple instances.
My code in the view:
public MyView() {
Mediator.Register("CloseWindow",()=>Close());
}
and in the ViewModel:
public SomeMethod() {
Mediator.Notify("CloseWindow");
}
This works find as long as there is only one instance of the View - ViewModel pair.
How do I solve it with multiple instances?
Solution
I use an alternative solution. MyView implements an interface IMyView which contains the Close method. The MyViewModel object associates the View and so it can call the Close method through the interface.
If you are interested in a concrete example then you might have a look at:
OTHER TIPS
I don't know how your particular implementation of the mediator pattern works, but in mine you can send more information than just strings.
For example:
public MyView() {
Mediator.Register<CloseWindowMessage>(message =>
{
if (message.ViewModel == DataContext) Close();
});
}
and in the ViewModel:
public SomeMethod() {
Mediator.Notify(new CloseWindowMessage(this));
}
In this example, the ViewModel passes itself as a parameter to the view. The view can then check that the message is being sent from its view model.