【问题标题】:MessengerInstance vs Messenger.Default in MvvmlightMvvmlight 中的 MessengerInstance 与 Messenger.Default
【发布时间】:2012-12-18 05:07:38
【问题描述】:

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

【问题讨论】:

    标签: mvvm-light


    【解决方案1】:

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

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

    希望这会有所帮助:)

    【讨论】:

      猜你喜欢
      • 2023-03-17
      • 1970-01-01
      • 2017-11-10
      • 1970-01-01
      • 2016-06-01
      • 2016-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多