问题
Is it possible to send a List in MVVM Light Message.
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.
回答1:
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; }
}
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 );
}
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);
Implement the callback method:
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));
}
You're done :)
来源:https://stackoverflow.com/questions/15599905/is-it-possible-to-send-a-listobject-in-mvvm-light-message