是否可以发送List< Object>在MVVM Light消息中 [英] Is it possible to send a List<Object> in MVVM Light Message

查看:40
本文介绍了是否可以发送List< Object>在MVVM Light消息中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在MVVM轻型消息中发送列表.

Is it possible to send a List in MVVM Light Message.

例如,我有一个名为Authors的类.我要发送

For example, I have a class named Authors. I want to send

Messenger.Default.Send(AuthorList); // AuthorList is of type List<Author>

在我正在编写的视图模型的构造函数中

in the constructor of the view model I am writing

Messenger.Default.Register<List<Author>>(this, authList => 
    {MessageBox.Show(authList[0].name)});

我已确保在发送消息之前调用了构造函数.但这似乎不起作用.

I have made sure that the constructor is called before I send the message. But it doesn't seem to work.

推荐答案

是. 创建您的类(我正在使用其中具有简单字符串属性的MyTest):

Yes . Create your class (I'm using MyTest which has a simple string property in it):

public partial class MyTest
{
    public MyTest(string some_string)
    {
        S = some_string;
    }

    public string S { get; set; }
}

您可以从任意位置调用它,在ViewModel中,我添加了一个按钮,它将创建该列表并将其发送到其他视图.

You can call it from wherever you want, in the ViewModel,I added a button that will create that list and send it to a different view.:

private void Button_Click(object sender, RoutedEventArgs e)
    {
        var list_of_objects = new List<MyTest> { new MyTest("one"), new MyTest("two") };
        Messenger.Default.Send(list_of_objects );
    }

在接收方的ViewModel上,将其添加到构造函数中以注册到该类型的消息,并创建一个在消息到达时将被调用的方法:

On the receiving ViewModel, add this in the constructor to register to that type of messages, and create a method that will be called when the message arrives:

// When a message with a list of MyTest is received
// this will call the ReceiveMessage method  :  
Messenger.Default.Register<List<MyTest>>(this, ReceiveMessage);

实施回调方法:

private void ReceiveMessage(List<MyTest> list_of_objects)
    {
        // Do something with them ... i'm printing them for example         
        list_of_objects.ForEach(obj => Console.Out.WriteLine(obj.S));
    }

您已经完成了:)

这篇关于是否可以发送List&lt; Object&gt;在MVVM Light消息中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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