Send a empty Message or Notification with MVVM toolkit light

后端 未结 4 850
故里飘歌
故里飘歌 2021-01-22 00:14

I\'m using the MVVM Light Toolkit. I could not find any Ctor of Messenger or Notification class to send a empty message.

ViewModel1:

 private int _select         


        
4条回答
  •  南方客
    南方客 (楼主)
    2021-01-22 01:20

    You can try sending a simple message with a string tag and receive that message by matching the string tag. Something like this:

    Sender portion of the code located possibly in something like ViewModel1.cs

    Messenger.Default.Send("Dummy text message", "String_ToHelpMatchTheMsg");
    

    Receiving end portion of the code responding to that message above, possibly located in some other file, something like ViewModel2.cs
    ...

    Messenger.Default.Register(this, "String_ToHelpMatchTheMsg", executeThisFunction);
    
    private void executeThisFunction(string strMsg)
    {
       //your code would go here to run upon receiving the message
       // The following line will display: "Dummy text message" 
       System.Windows.Browser.HtmlPage.Window.Alert("msg passed: " + strMsg); 
    }
    

    Please note that you dont have to do anything with the text message that is passed around with the messaging code above. Just one part of the code sending some ping to another part of the code to ask some other section to execute some code. The important string is the one where I used "String_ToHelpMatchTheMsg" because that is the key used to match the sender and the receiver. Almost like creating your own quasi-event, once the Send method runs, the Register method is notified and fire its own function to run also.

    I used this with a Close button on a Child Window to close it. The Close button on the View of the Child Window binds to a relay command on its childWindowViewModel. That relay command has the code above to send a message to the ParentViewModel. The Register portion on the ParentViewModel responds to that message by firing a method that closes the ChildWindow which was initially instantied from that parentViewModel.

    Once you get more familiar with messaging, there are more attributes that you will be able to use so that the receiver can call back the sender to give a status or some data back. Look for Delegates and lambda function to achieve this.

    All this to avoid placing code in the code behind to close the child window! :-) Use as you see fit.

    Cheers. Mario

提交回复
热议问题