简体   繁体   中英

MVVM Mediator multiple instances

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?

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM