Skip to content

ViewModel: Mediators

Raphael Winkler edited this page May 29, 2022 · 1 revision

Let's say you have two viewmodels with the following properties:

  • UserListViewModel
    • List Users
  • UserCreateViewModel
    • string Name

Now, if we create a new user inside the "UserCreateViewModel", how can we make sure the "UserListViewModel" receives our new user? With the Mediator class of course! In this example we will hook up the notification pipeline by using "Mediator.Instance.NotifyColleagues(...)" and "Mediator.Instance.Register(...)".

Setting up an Enum for Mediator

First of all we need a new enum class for this. We will need this enum to notify and register notifications, but more on that later. As we just need to transfer the Name variable, we will create something like this:

public enum MediatorEnum
{
    UserCreated
}

Now that we have our enum, we can start using the Mediator. For our example, we want to transfer the "Name" property from "UserCreateViewModel" to the "Users" list inside "UserListViewModel". First we register notifications for "MediatorEnum.UserCreated" inside the constructor of "UserListViewModel". (please note that some code has been left out, so we can better focus on the Mediator part)

public UserListViewModel : ViewModelBase
{
    ...

    public UserListViewModel()
    {
        // Register for notifications for "MediatorEnum.UserCreated". The first variable is our delegate, which in turn contains the message content
        Mediator.Instance.Register(o =>
        {
            // Here we check and parse the object "o" into a string and add it to our user list
            if (o is string value)
            {
                Users.Add(value);
            }
        }, MediatorEnum.UserCreated);
    }
}

But registering is only halve the equation, the last step is actually notifying. In this example we assume that we have a view behind our viewmodel, with a button that calls the "SaveUser()" method inside the viewmodel:

public UserCreateViewModel : ViewModelBase
{
    ...

    public string Name
    {
        get { ... }
        set { ... }
    }

    public void SaveUser()
    {
        // Notify every colleague that is registered to the notification pipeline "MediatorEnum.UserCreated".
        Mediator.Instance.NotifyColleagues(MediatorEnum.UserCreated, Name);
    }
}

And with this we are done! Now every time the method "SaveUser()" inside "UserCreateViewModel" is called, a notification is sent out to every colleague which registered to the notification pipeline "MediatorEnum.UserCreated". This in turn triggers the "Register" delegate inside our "UserListViewModel", and we can pull our new variable from the object "o".