7

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

4

1 回答 1

3

MessengerInstanceRaisePropertyChanged() 方法使用:

<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);

您可以在视图模型 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);
        }
    }

抓住它并在视图模型 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;
        });

希望这会有所帮助:)

于 2012-12-18T09:51:32.000 回答