gpt4 book ai didi

mvvm - MVVM Light Messenger-发送和注册对象

转载 作者:行者123 更新时间:2023-12-03 08:46:57 24 4
gpt4 key购买 nike

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

最佳答案

微软的Jesse Liberty在如何利用MVVM Light内的消息传递方面有一个很棒的concrete walk through。前提是创建一个类,该类将充当您的消息类型,然后订阅,然后发布。

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

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

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

现在,您可以注册给定的消息类型,该类型与上面定义的类相同,并提供在收到消息时将调用的方法,在这种情况下为 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 - MVVM Light Messenger-发送和注册对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16993918/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com