是否可以在MVVM Light Message中发送List。
例如,我有一个名为Authors的类。我想发送
Messenger.Default.Send(AuthorList); // AuthorList is of type List<Author>
在我正在编写的视图模型的构造函数中
Messenger.Default.Register<List<Author>>(this, authList =>
{MessageBox.Show(authList[0].name)});
我确保在发送消息之前调用构造函数。但它似乎没有用。
答案 0 :(得分:2)
是的。 创建你的类(我正在使用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上,在构造函数中添加它以注册到该类型的消息,并创建一个在消息到达时将被调用的方法:
// 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));
}
你已经完成了:)