ViewModel and Interaction Processing (Messenger)

1 minute read

Introduction

Memorandum of Interpretation of Oreore Part 13

I will summarize Messanger, which is an implementation for interaction processing provided by Livet.

Text

As I introduced at the end of Last time, Livet is one of the MVVM frameworks like Prism.
Livet provides a mechanism called Messanger, which allows you to request interaction from ViewModel without directly referencing the View.
Let’s use this as an alternative to InteractionRequest, which is obsolete in Prism 7.2.

The implementation method is different between Messanger and InteractionRequest. Messanger has one instance itself, and the difference in processing is expressed by the MessageKey specified when notifying from ViewModel. View handles notifications and performs interaction processing by binding Messanger and specifying a value for MessageKey.

Compared to InteractionRequest, Messenger has a cleaner implementation because it can reduce the number of instances. On the other hand, you need to specify the MessageKey as a string, and you may have different tastes in this area.

ViewModel


using Livet.Messaging;

namespace TestApp.ViewModels
{
    public class MainWindowViewModel
    {
        public InteractionMessenger Messanger { get; }

        public MainWindowviewModel()
        {
            this.Messenger = new InteractionMessenger();
        }

        public void ShowMessage()
        {
            this.Messenger.Raise(new InteractionMessage("ShowMessage"));
        }
    }
}

View


<Window x:Class="TestApp.Views.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
        xmlns:p="http://prismlibrary.com/"
        xmlns:behaviors="clr-namespace:TestApp.Views.Behaviors"
        p:ViewModelLocator.AutoWireViewModel="True">
    <i:Interaction.Triggers>
        <l:InteractionMessageTrigger MessageKey="ShowMessage" Messenger="{Binding Messenger, Mode=OneWay}">
            <behaviors:MessageAction/>
        </l:InteractionMessageTrigger>
    </i:Interaction.Triggers>
</Window>

in conclusion

We talked about Livet’s Messager.
Like InteractionRequest, it’s a very versatile mechanism and should provide strong support for MVVM pattern development.