Use MVVM Light's Messenger to Pass Values Between View Model

前端 未结 1 1705
渐次进展
渐次进展 2020-12-01 06:49

Could someone be so kind as to explain MVVM Light\'s Messenger for me? I was reading a post on StackOverflow here: MVVM pass values between view models trying to get this. T

相关标签:
1条回答
  • 2020-12-01 07:35

    Say I have two ViewModels and a ViewModelLocator. I want to be able to pass parameters between all three without issue. How would I go about doing this with the messenger? Is it capable of that?

    That's exactly what it's for, yes.

    To send a message:

    MessengerInstance.Send(payload, token);
    

    To receive a message:

    MessengerInstance.Register<PayloadType>(
        this, token, payload => SomeAction(payload));
    

    There are many overloads, so without knowing exactly what you're trying to accomplish via the messenger, I won't go into all of them, but the above should cover the simple case of wanting to send and receive a message with a payload.

    Note that "token" can be really anything that identifies the message. While a string is often used for this, I prefer to use an enum because it's a little safer and enables intellisense, "find usages", etc.

    For example:

    public enum MessengerToken
    {
        BrushChanged,
        WidthChanged,
        HeightChanged
    }
    

    Then your send/receive would be something like:

    // sending view model
    MessengerInstance.Send(Brushes.Red, MessengerToken.BrushChanged);
    
    // receiving view model
    
    // put this line in the constructor
    MessengerInstance.Register<Brush>(this, token, brush => ChangeColor(brush));
    
    public void ChangeColor(Brush brush)
    {
        Brush = brush;
    }
    

    [EDIT] URL to devuxer's comment below changed to: http://blog.galasoft.ch/posts/2009/09/mvvm-light-toolkit-messenger-v2/

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