Mvvmlight中的MessengerInstance与Messenger.Default

kid*_*dgu 7 mvvm-light

在MvvmLight中,我发现除了Messenger.Default这是一种存储整个应用程序的消息句柄的全局静态变量之外,每个Viewmodel都会有另一个名为MessengerInstance的Messenger Handler.所以,我对于使用的MessengerInstance以及如何使用它感到困惑?(只有ViewModel可以看到它 - >谁将收到并处理消息?)

小智 3

MessengerInstance由 RaisePropertyChanged() 方法使用:

<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);
Run Code Online (Sandbox Code Playgroud)

您可以在视图模型 B 的属性上使用它,例如:

    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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

捕获它并在视图模型 A 上处理它:

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;
        });
Run Code Online (Sandbox Code Playgroud)

希望这会有所帮助:)