MVVM Light Messenger-发送和注册对象 [英] MVVM Light Messenger - Sending and Registering Objects

查看:206
本文介绍了MVVM Light Messenger-发送和注册对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人能为我提供一个示例,说明如何使用MVVM Light的Messenger来在类之间发送和注册自定义对象,或为我提供涵盖此内容的教程(最好是一个具体示例)吗?我一直在尝试使用Messenger将项目中的对象传递给另一个类,但是我从未成功过.我在网上寻找示例,但没有找到任何能说明我需要的东西.谢谢.

Could somebody be kind enough to give me an example of how to Send and Register custom objects between classes using MVVM Light's Messenger or point me to a tutorial that covers this (preferably a concrete example)? I've been trying to use Messenger to pass an object in my project to another class but I've never been successful at it. I've looked online for examples but haven't found anything that shows me what I need. Thanks.

推荐答案

Microsoft的Jesse Liberty具有出色的

Jesse Liberty of Microsoft has a great concrete walk through on how to make use of the messaging within MVVM Light. The premise is to create a class which will act as your message type, subscribe, then publish.

public class GoToPageMessage
{
   public string PageName { get; set; }
}

这实际上将根据上述类型/类发送消息...

This will essentially send the message based on the above type/class...

private object GoToPage2()
{
   var msg = new GoToPageMessage() { PageName = "Page2" };
   Messenger.Default.Send<GoToPageMessage>( msg );
   return null;
}

现在您可以注册给定的消息类型,该类型与上面定义的类相同,并提供在收到消息时将被调用的方法,在这种情况下为ReceiveMessage.

Now you can register for the given message type, which is the same class defined above and provide the method which will get called when the message is received, in this instance ReceiveMessage.

Messenger.Default.Register<GoToPageMessage>
( 
     this, 
     ( action ) => ReceiveMessage( action ) 
);

private object ReceiveMessage( GoToPageMessage action )
{
   StringBuilder sb = new StringBuilder( "/Views/" );
   sb.Append( action.PageName );
   sb.Append( ".xaml" );
   NavigationService.Navigate( 
      new System.Uri( sb.ToString(), 
            System.UriKind.Relative ) );
   return null;
}

这篇关于MVVM Light Messenger-发送和注册对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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