简体   繁体   English

MVVM介体多个实例

[英]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: 并在ViewModel中:

public SomeMethod() {
    Mediator.Notify("CloseWindow");
}

This works find as long as there is only one instance of the View - ViewModel pair. 只要只有View-ViewModel对的一个实例,就可以找到此项目。

How do I solve it with multiple instances? 如何解决多个实例?

I use an alternative solution. 我使用替代解决方案。 MyView implements an interface IMyView which contains the Close method. MyView实现了一个包含Close方法的接口IMyView。 The MyViewModel object associates the View and so it can call the Close method through the interface. MyViewModel对象关联了View,因此它可以通过该接口调用Close方法。

If you are interested in a concrete example then you might have a look at: 如果您对一个具体示例感兴趣,那么可以看看:

WPF Application Framework (WAF) WPF应用程序框架(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: 并在ViewModel中:

public SomeMethod() {
    Mediator.Notify(new CloseWindowMessage(this));
}

In this example, the ViewModel passes itself as a parameter to the view. 在此示例中,ViewModel将自身作为参数传递给视图。 The view can then check that the message is being sent from its view model. 然后,视图可以检查是否正在从其视图模型发送消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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