Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MessengerInstance vs Messenger.Default in Mvvmlight

Tags:

mvvm-light

In MvvmLight, I found that beside Messenger.Default which is a kind of global static variable to store the message handle of whole application, each Viewmodel will have another Messenger Handler named MessengerInstance. So, I'm confused about what is MessengerInstance used for & how to use it? (Only ViewModel can see it --> who will receive & process message?)

like image 277
kidgu Avatar asked Dec 18 '12 05:12

kidgu


1 Answers

The MessengerInstance is used by the RaisePropertyChanged() method :

<summary>
/// Raises the PropertyChanged event if needed, and broadcasts a
///             PropertyChangedMessage using the Messenger instance (or the
///             static default instance if no Messenger instance is available).
/// 
/// </summary>
/// <typeparam name="T">The type of the property that
///             changed.</typeparam>
/// <param name="propertyName">The name of the property 
///             that changed.</param>
/// <param name="oldValue">The property's value before the change
///             occurred.</param>
/// <param name="newValue">The property's value after the change
///             occurred.</param>
/// <param name="broadcast">If true, a PropertyChangedMessage will
///             be broadcasted. If false, only the event will be raised.</param>
protected virtual void RaisePropertyChanged<T>(string propertyName, T oldValue, T    
                                               newValue, bool broadcast);

You can use it on a property on a view model B for example :

    public const string SelectedCommuneName = "SelectedCommune";

    private communes selectedCommune;

    public communes SelectedCommune
    {
        get { return selectedCommune; }

        set
        {
            if (selectedCommune == value)
                return;

            var oldValue = selectedCommune;
            selectedCommune = value;

            RaisePropertyChanged(SelectedCommuneName, oldValue, value, true);
        }
    }

Catch it and deal with it on a view model A with :

Messenger.Default.Register<PropertyChangedMessage<communes>>(this, (nouvelleCommune) =>
        {
            //Actions to perform
            Client.Ville = nouvelleCommune.NewValue.libelle;
            Client.CodePays = nouvelleCommune.NewValue.code_pays;
            Client.CodePostal = nouvelleCommune.NewValue.code_postal;
        });

Hope this will help :)

like image 166
Romain Avatar answered Oct 21 '22 03:10

Romain