tags:

views:

349

answers:

2

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?

A: 

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.

Groky
I thought of that but I think it becomes to much of an opt-in strategy. I am leaning towards a solution where I unregister from messages in the Close event.
adrianm
Or you could create a separate message class for each dialog then to avoid the "opt-in"-ness.
Groky
+1  A: 

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:

WPF Application Framework (WAF)

jbe
I choose the mediator pattern because it seemed simpler than interfaces and that I can use it both for vertical (MV<->V) and horisontal (MV<->MV). I see now that it was wrong and will use interfaces instead. The mediator pattern is fundamentally broken (at least for views) in my opinion. The mediator use GC for lifetime control while the views do not. The answer is therefore to not use mediator for views.
adrianm