【问题标题】:Is it possible to send a List<Object> in MVVM Light Message是否可以在 MVVM Light Message 中发送 List<Object>
【发布时间】:2013-03-14 01:18:43
【问题描述】:

是否可以在 MVVM Light Message 中发送列表。

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

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

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

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

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

【问题讨论】:

  • 您是否收到错误消息?我认为您需要明确说明要发送的类型。 Messenger.Default.Send&lt;List&lt;Author&gt;&gt;(AuthorList);
  • 我试过明确说明发送类型。这没有帮助。
  • 你能否毫无问题地将其他(非列表)消息发送到同一个 ViewModel?

标签: wpf mvvm mvvm-light


【解决方案1】:

是的。 创建你的类(我正在使用其中有一个简单字符串属性的 MyTest):

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

    public string S { get; set; }
}

您可以从任何地方调用它,在 ViewModel 中,我添加了一个按钮,该按钮将创建该列表并将其发送到不同的视图。:

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 上,在构造函数中添加 this 以注册到该类型的消息,并创建将在消息到达时调用的方法:

// 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));
    }

你已经完成了:)

【讨论】:

  • 感谢您对问题的精彩回答。当我实现它时,它抱怨 RecieveMessage 类型并说它应该是 Action 类型。我应该在接收消息的 ViewModel 中实现回调方法吗?以及我的代码有什么问题: Messenger.Default.Register(_profileList , ReceiveMessage) ......................... Private sub ReceiveMessage(ProfileListt As List (个人资料)) _profileList =ProfileListt End sub ---------------------------------------- - - 谢谢。 (我的代码是VB)
  • 好吧,我不熟悉 VB,哇,我回答这个问题已经 6 年了。 VB()是否等于C#&lt;&gt;,因为上面的代码注册了一个泛型类型。对不起,我不能给你更好的答案。否则可能会为您的 VB 问题打开一个新问题?
  • 我认为语法是正确的,但是对于在接收对象的视图模型中注册,它并没有让我放置 ReceiveMessage 函数。它说它应该是一个动作!我想它可能有一个简单的答案。还是谢谢你的回复。
  • 在c#中,动作是一种不返回任何东西的方法(相对于函数,它返回一些东西)。所以,也许在您的注册中您需要简单地传递函数的名称?你必须搜索它,但它听起来不错。抱歉,我帮不上忙
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多