How to use MVVM-Light with tokens?

后端 未结 2 1989
隐瞒了意图╮
隐瞒了意图╮ 2020-12-29 15:50

I see in the MVVM-Light package that I can send messages with tokens- what I need to do is send an object, with a message attached to that object- like Add, Edit, Delete wha

相关标签:
2条回答
  • 2020-12-29 16:06

    Here is a quick section of code for both the send and the register. Your Notification is the message that instructs the receiver what the intention was. The Content is the item you wanted to send, and you can further identify who sent the message, and even what object this message was intended for with the sender and the target.

    Messenger.Default.Send<NotificationMessage<Job>>(
        new NotificationMessage<Job>(this, myJob, "Add")
    );
    
    Messenger.Default.Register<NotificationMessage<Job>>(
    this, nm =>
    
    {
        // this might be a good idea if you have multiple recipients.
        if (nm.Target != null &&
            nm.Target != this)
            return;
    
        // This is also an option 
        if (nm.Sender != null &&
            nm.Sender != expectedFrom) // expectedFrom is the object whose code called Send
            return;
    
        // Processing the Message
        switch(nm.Notification)
        {
            case "Add":
                Job receivedJob = nm.Content;
                // Do something with receivedJob
                break;
            case "Delete":
                Job receivedJob = nm.Content;
                // Do something with receivedJob
                break;
        }
    });
    
    0 讨论(0)
  • 2020-12-29 16:20

    Just as an addition: The token is not meant to identify a task (notification), but rather a receiver. The receiver(s) who register(s) with the same token as the sender will get the message, while all other receivers won't get it.

    For what you want to do, I use the optional NotificationMessage type included in the toolkit. It has an additional string property (Notification) that you can set to anything you want. I use this to "give orders" to the receiver.

    Cheers, Laurent

    0 讨论(0)
提交回复
热议问题