gpt4 book ai didi

mvvm-light - Mvvmlight 中的 MessengerInstance 与 Messenger.Default

转载 作者:行者123 更新时间:2023-12-04 12:42:01 26 4
gpt4 key购买 nike

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

最佳答案

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

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

捕获它并在 View 模型 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;
});

希望这会有所帮助:)

关于mvvm-light - Mvvmlight 中的 MessengerInstance 与 Messenger.Default,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13926645/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com