从另一个viewmodel调用一个代码方法 [英] Call a method of code behind from another viewmodel

查看:175
本文介绍了从另一个viewmodel调用一个代码方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个View MyView 和相应的ViewModel MyViewModel 。在 MyView 上方有横幅(用户控件)。横幅被许多视图使用。它的功能是显示通知。横幅代码后面有一个方法。



现在我在 MyView 中有一个按钮命令。我想按它并向该方法发送消息。 button命令的实现在 MyViewModel



那么如何从 MyViewModel 调用该方法? br $> b $ b

请不要告诉我这是针对MVVM的。我知道但现在别无选择。



我的尝试:



c# - 我如何访问在viewmodel中控制mvvm模型? - 堆栈溢出 [ ^ ]这个很有帮助。但不确定它是否适合我的情况。

I have a View MyView and corresponding ViewModel MyViewModel. Above the MyView there is banner(user control). The banner is used by many views. Its function is to display notifications. There is a method inside the banner's code behind.

Now I have a button command in the MyView. I want to press it and send a message to the method. The implementation of the button command is in MyViewModel.

So how to call the method from MyViewModel?

Please don't tell me it is against MVVM. I know it but no choice right now.

What I have tried:

c# - How can i access a control in mvvm model in viewmodel? - Stack Overflow[^] This one is helpful. But not sure it is fitful my case.

推荐答案

banner只是另一个视图;我看到没有问题插入其他视图。



应该有它自己的模型响应其他模型发布的传入消息 (或其他)。



您似乎不将其视为视图而是视为用户控件(?);因此你的不快乐。
The "banner" is just another "view"; I see no issue slotting in with the "other views".

It should have it's own "model" that responds to "incoming messages" posted from "other models" (or whatever).

You do not appear to be treating it as a view but as a "user control" (?); and therefore your unhappiness.


我的方法,就是它的价值,就是做这样的事情。使用 Prism.Events ,声明一个事件。在以下示例中,事件的有效负载是 bool 但您可以使用任何对象。

My approach, for what it's worth, would be to do something like this. Using Prism.Events, declare an event. In the following example the event's payload is a bool but you can use any object.

public class DatabaseServiceIsSavedEvent : PubSubEvent<bool>
   {

   }



中希望发布事件,有一个 IEventAggregator聚合器的实例然后,当你想举起事件时,你可以发布这样的事件。



In the class that wishes to publish the event, have an instance of IEventAggregator aggregator then, when you want to raise the event, you can publish the event like this.

aggregator.GetEvent<DatabaseServiceIsSavedEvent>().Publish(true);



在这种情况下,有效负载是 bool 设置为 true


在您希望收到活动的的构造函数中,您订阅了该活动,传递引发事件时希望调用的方法。例如。


In this case the payload is a bool set to true.

In the constructor of the class that you wish to receive the event, you subscribe to the event, passing in the method that you wish to be called when the event is raised. For example.

aggregator.GetEvent<DatabaseServiceIsSavedEvent>()
              .Subscribe(OnIsSavedEvent);



OnIsSavedEvent 方法是这样的。


The OnIsSavedEvent method is something like this.

public void OnIsSavedEvent(bool isSaved)
       {
           IsModified = !isSaved;
       }


这篇关于从另一个viewmodel调用一个代码方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆